使用复杂体系结构解析 .NET 程序集



希望有人能回答这个问题。

我有一个具有此体系结构的应用程序:

API 库(类库) 已使用的库版本 2(由 ApiLibrary 引用的类库)

然后,我的 ApiLibrary 有一个第三方插件系统。 开发人员可以创建自定义插件,引用 ApiLibrary 并扩展名为"AbstractPlugin"的抽象类型。 有一个特定的文件夹(插件),用户可以在其中放置子文件夹,它们本身包含为插件生成的 dll。

我的API有一个专用的方法来加载这些插件,循环访问此文件夹中的所有dlls文件并使用"Assembly.LoadFile(currentDll)"。 然后,它循环程序集中的所有类型,并尝试查找从 AbstractPlugin 扩展的类型。找到的所有这些类型都是可以在 API 中使用的插件。

插件不应将 ApiLibrary 的输出包含在放置它们的文件夹中(向开发人员指定要求)。为了确保在调用插件函数时有效地解析我的 API,我处理了 AppDomain.CurrentDomain.AssemblyResolve 事件并返回正在执行的程序集。 但是他们可以在他们的文件夹中包含其他库的dll。

问题是现在,我有一个插件实际上需要引用"UsedLibrary",但在版本 1 中。 然后,如果在加载插件之前在我的 ApiLibrary 中调用了 UsedLibrary 中的函数,则会加载版本 2,并且插件将无法工作,因为它需要版本 1。 此外,如果之前加载了插件,则会加载版本 1,我的 API 无法使用 v2 中的函数。

事实上,我简化了这个问题,因为它确实更复杂,因为 UsedLibrary 动态加载自己放置在我的 API 主文件夹上的非托管库,并且插件应该从自己的文件夹加载非托管库。

我想知道是否有人有解决方案来确保我的插件能够从 v1 调用函数,我的 API 将从 v2 调用函数(我无法重命名这些程序集)。

谢谢。

编辑 1:

我尝试在每个插件文件夹的不同应用程序域中加载 DLL,但经过多次尝试,最终无法获得我的程序集。如何使用这种代码在不同的应用程序域中加载程序集:

loadedAssemblies = new Dictionary<string, Assembly>();
UriBuilder uri = new UriBuilder(Assembly.GetExecutingAssembly().CodeBase);
string basePath = Path.GetDirectoryName(Uri.UnescapeDataString(uri.Path));
foreach (string fullPluginPath in Directory.EnumerateDirectories(PLUGINS_PATH))
{
string pluginFolder = Path.GetFileName(fullPluginPath);
AppDomainSetup setup = new AppDomainSetup();
setup.ApplicationName = pluginFolder;
setup.ApplicationBase = basePath;
setup.PrivateBinPath = fullPluginPath;
System.Security.PermissionSet permissionSet = new System.Security.PermissionSet(System.Security.Permissions.PermissionState.Unrestricted);
AppDomain pluginAppDomain = AppDomain.CreateDomain(pluginFolder, null, setup, permissionSet);
foreach (string fileName in Directory.EnumerateFiles(fullPluginPath))
{
if (Path.GetExtension(fileName.ToLower()) == ".dll")
{
try
{
Assembly currentAssembly = ??; // How to load the assembly within the plugin app domain ???
loadedAssemblies.Add(currentAssembly.FullName, currentAssembly);
}
catch (Exception e)
{
// DLL could not be loaded
}
}
}
}

谢谢。

编辑 2:

我终于明白了如何在AppDomain之间进行通信,并且可以加载程序集并在其中查找插件,但是我仍然遇到问题。

插件由我的 API(类库)通过 PluginsManager 对象加载:

/// <summary>
/// A plugin manager can be used by the holding application using the API to gain access to plugins installed by the user.
/// All errors detected during plugins loading are stored, so applications may know when a plugin could not be loaded.
/// </summary>
public class PluginsManager : MarshalByRefObject
{
/// <summary>
/// Name of the plugins folder.
/// </summary>
private const string PLUGIN_FOLDER = "ApiPlugins";
#region Fields
/// <summary>
/// Plugins loaded and initialised without errors
/// </summary>
private List<AbstractPlugin> loadedPlugins;
/// <summary>
/// Dictionary of errors detected during DLL parsings.
/// </summary>
private Dictionary<string, Exception> dllLoadException;
/// <summary>
/// Dictionary of errors detected during assemblies types parsing.
/// </summary>
private Dictionary<string, Exception> assembliesTypesLoadExceptions;
/// <summary>
/// Dictionary of errors detected during plugins instance creation.
/// </summary>
private Dictionary<string, Exception> pluginsConstructionExceptions;
/// <summary>
/// Dictionary of errors detected during plugins instance creation.
/// </summary>
private Dictionary<string, Exception> pluginsRetrievalExceptions;
/// <summary>
/// Dictionary of errors detected during plugins initialisation.
/// </summary>
private Dictionary<string, Exception> pluginsInitialisationExceptions;
/// <summary>
/// The currently loaded DLL during plugins reload.
/// Used to resolve assembly in the current domain when loading an assembly containing IDM-CIC plugins.
/// </summary>
private static string currentlyLoadedDll = null;
#endregion
#region Methods
public void LoadPlugins()
{
// Ensures assemblies containing plugins will be loaded in the current domain
AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;
try
{
List<PluginLoader> pluginLoaders = new List<PluginLoader>();
loadedAssemblies = new Dictionary<string, Assembly>();
loadedPlugins = new List<AbstractPlugin>();
dllLoadException = new Dictionary<string, Exception>();
assembliesTypesLoadExceptions = new Dictionary<string, Exception>();
pluginsInitialisationExceptions = new Dictionary<string, Exception>();
pluginsConstructionExceptions = new Dictionary<string, Exception>();
pluginsRetrievalExceptions = new Dictionary<string, Exception>();
string pluginsFolderPath = Path.Combine("C:", PLUGIN_FOLDER);
UriBuilder uri = new UriBuilder(Assembly.GetExecutingAssembly().CodeBase);
string basePath = Path.GetDirectoryName(Uri.UnescapeDataString(uri.Path));
// detect automatically dll files in plugins folder and load them.
if (Directory.Exists(pluginsFolderPath))
{
foreach (string pluginPath in Directory.EnumerateDirectories(pluginsFolderPath))
{
string pluginFolderName = Path.GetFileName(pluginPath);
AppDomainSetup setup = new AppDomainSetup();
setup.ApplicationName = pluginFolderName;
setup.ApplicationBase = basePath;
setup.PrivateBinPath = pluginPath;
PermissionSet permissionSet = new PermissionSet(PermissionState.Unrestricted);
AppDomain pluginAppDomain = AppDomain.CreateDomain(pluginFolderName, AppDomain.CurrentDomain.Evidence, setup, permissionSet);
foreach (string dllFile in Directory.EnumerateFiles(pluginPath, "*.dll", SearchOption.TopDirectoryOnly))
{
try
{
currentlyLoadedDll = dllFile;
PluginLoader plugLoader = (PluginLoader)pluginAppDomain.CreateInstanceAndUnwrap(Assembly.GetExecutingAssembly().FullName, typeof(PluginLoader).FullName);
Assembly ass = plugLoader.LoadAssemblyIfItContainsPlugin(dllFile);
if (ass != null)
{
pluginLoaders.Add(plugLoader);
}
// Check types parsing exceptions and store them
if (plugLoader.CaughtExceptionOnTypesParsing != null)
{
assembliesTypesLoadExceptions.Add(plugLoader.LoadedAssemblyName, plugLoader.CaughtExceptionOnTypesParsing);
}
}
catch (Exception e)
{
// Store problem while loading a DLL
dllLoadException.Add(dllFile, e);
}
}
}
}
foreach (PluginLoader plugLoader in pluginLoaders)
{
// Load all plugins of the loaded assembly
plugLoader.LoadAllPlugins();
// Check plugins construction errors and store them
foreach (KeyValuePair<Type, Exception> kvp in plugLoader.CaughtExceptionOnPluginsCreation)
{
Type type = kvp.Key;
Exception e = kvp.Value;
pluginsConstructionExceptions.Add(type.Name + " from " + plugLoader.LoadedAssemblyName, e);
}
for (int i = 0; i < plugLoader.GetPluginsCount(); i++)
{
AbstractPlugin plugin = null;
try
{
// Try to retrieve the plugin in our context (should be OK because AbstractPlugin extends MarshalByRefObject)
plugin = plugLoader.GetPlugin(i);
}
catch (Exception e)
{
// Store the retrieval error
pluginsRetrievalExceptions.Add(plugLoader.GetPluginName(i) + " from " + plugLoader.LoadedAssemblyName, e);
}
if (plugin != null)
{
try
{
// Initialise the plugin through the exposed method in AbstractPlugin type and that can be overridden in plugins
plugin.Initialise();
loadedPlugins.Add(plugin);
}
catch (Exception e)
{
// Store the initialisation error
pluginsInitialisationExceptions.Add(plugin.GetType().Name, e);
}
}
}
}
}
finally
{
AppDomain.CurrentDomain.AssemblyResolve -= CurrentDomain_AssemblyResolve;
}
}

/// <summary>
/// Ensure plugins assemblies are loaded also in the current domain
/// </summary>
/// <param name="sender">Sender of the event</param>
/// <param name="args">Arguments for assembly resolving</param>
/// <returns>The resolved assembly or null if not found (will result in a dependency error)</returns>
private Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
{
AssemblyName assemblyName = new AssemblyName(args.Name);
if (args.RequestingAssembly == null && assemblyName.Name.ToLower() == Path.GetFileNameWithoutExtension(currentlyLoadedDll).ToLower())
{
return Assembly.LoadFrom(currentlyLoadedDll);
}
return null;
}
/// <summary>
/// Enumerates all plugins loaded and initialised without error.
/// </summary>
/// <returns>Enumeration of AbstractPlugin</returns>
public IEnumerable<AbstractPlugin> GetPlugins()
{
return loadedPlugins;
}
#endregion
}

帮助检索插件的 PluginLoader 对象描述如下:

/// <summary>
/// This class is internally used by the PluginsManager to load an assembly though a DLL file and load an instance of each plugins that can be found within this assembly.
/// </summary>
internal class PluginLoader : MarshalByRefObject
{
#region Fields
/// <summary>
/// The assembly loaded within this plugin loader. 
/// Null if could not be loaded or does not contains any plugin.
/// </summary>
private Assembly loadedAssembly = null;
/// <summary>
/// Exception caught when trying to parse assembly types.
/// Null if GetTypes() was successfull.
/// </summary>
private Exception caughtExceptionOnTypesParsing = null;
/// <summary>
/// Dictionary of exceptions caught when trying ti instantiate plugins.
/// The key is the plugin type and the value is the exception.
/// </summary>
private Dictionary<Type, Exception> caughtExceptionOnPluginsCreation = new Dictionary<Type, Exception>();
/// <summary>
/// The list of loaded plugins that is filled when calling the LoadAllPlugins method.
/// </summary>
private List<AbstractPlugin> loadedPlugins = new List<AbstractPlugin>();
#endregion
#region Accessors
/// <summary>
/// Gets the loaded assembly name if so.
/// </summary>
public string LoadedAssemblyName
{
get { return loadedAssembly != null ? loadedAssembly.FullName : null; }
}
/// <summary>
/// Gets the exception caught when trying to parse assembly types.
/// Null if GetTypes() was successfull.
/// </summary>
public Exception CaughtExceptionOnTypesParsing
{
get { return caughtExceptionOnTypesParsing; }
}
/// <summary>
/// Gets an enumeration of exceptions caught when trying ti instantiate plugins.
/// The key is the plugin type and the value is the exception.
/// </summary>
public IEnumerable<KeyValuePair<Type, Exception>> CaughtExceptionOnPluginsCreation
{
get { return caughtExceptionOnPluginsCreation; }
}
#endregion
#region Methods
/// <summary>
/// Loads an assembly through a DLL path and returns it only if it contains at least one plugin.
/// </summary>
/// <param name="assemblyPath">The path to the assembly file</param>
/// <returns>An assembly or null</returns>
public Assembly LoadAssemblyIfItContainsPlugin(string assemblyPath)
{
// Load the assembly
Assembly assembly = Assembly.LoadFrom(assemblyPath);
IEnumerable<Type> types = null;
try
{
types = assembly.GetTypes();
}
catch (Exception e)
{
// Could not retrieve types. Store the exception
caughtExceptionOnTypesParsing = e;
}
if (types != null)
{
foreach (Type t in types)
{
if (!t.IsAbstract && t.IsSubclassOf(typeof(AbstractPlugin)))
{
// There is a plugin. Store the loaded assembly and return it.
loadedAssembly = assembly;
return loadedAssembly;
}
}
}
// No assembly to return
return null;
}
/// <summary>
/// Load all plugins that can be found within the assembly.
/// </summary>
public void LoadAllPlugins()
{
if (caughtExceptionOnTypesParsing == null)
{
foreach (Type t in loadedAssembly.GetTypes())
{
if (!t.IsAbstract && t.IsSubclassOf(typeof(AbstractPlugin)))
{
AbstractPlugin plugin = null;
try
{
plugin = (AbstractPlugin)Activator.CreateInstance(t);
}
catch (Exception e)
{
caughtExceptionOnPluginsCreation.Add(t, e);
}
if (plugin != null)
{
loadedPlugins.Add(plugin);
}
}
}
}
}
/// <summary>
/// Returns the number of loaded plugins.
/// </summary>
/// <returns>The number of loaded plugins</returns>
public int GetPluginsCount()
{
return loadedPlugins.Count;
}
/// <summary>
/// Returns a plugin name from its index in the list of loaded plugins.
/// </summary>
/// <param name="index">The index to search</param>
/// <returns>The name of the corresponding plugin</returns>
public string GetPluginName(int index)
{
return loadedPlugins[index].Name;
}
/// <summary>
/// Returns a plugin given its index in the list of loaded plugins.
/// </summary>
/// <param name="index">The index to search</param>
/// <returns>The loaded plugin as AbstractPlugin</returns>
public AbstractPlugin GetPlugin(int index)
{
return loadedPlugins[index];
}
#endregion
}

我注意到,为了确保通信,所有可以在当前域和插件域之间传递的对象都必须扩展 MarshalByRefObject clas(或具有可序列化属性,但我想在 AppDomain 之间进行通信而不是复制当前域中的对象)。这样做没关系,我确保所有需要的对象都扩展了 MarshalByRefObject 类型。

此 API 由用户应用程序(另一个 Visual Studio 项目)引用,该应用程序调用 PluginsManager 来加载所有插件并迭代加载的插件。

它可以成功加载和迭代所有插件,但在 AbstractPlugin 类型中,我有必须由应用程序处理的特定事件。在这些事件上创建句柄时,我有一个序列化异常...

这是我应用程序中的插件控制器:

/// <summary>
/// This controller helps to load all plugins and display their controls within the application
/// </summary>
internal class PluginsController
{
/// <summary>
/// A plugins manager that helps to retrieve plugins
/// </summary>
private PluginsManager pluginsManager = new PluginsManager();
/// <summary>
/// Initialise the list of available plugins and create all needed controls to the application
/// </summary>
internal void InitialisePlugins()
{
pluginsManager.LoadPlugins();
foreach (AbstractPlugin plugin in pluginsManager.GetPlugins())
{
// Treat my plugin data, adding controls to the application
// ...
// Handle events on the plugin : EXCEPTION
plugin.OnControlAdded += plugin_OnControlAdded;
plugin.OnControlChanged += plugin_OnControlChanged;
plugin.OnControlRemoved += plugin_OnControlRemoved;
}
}
void plugin_OnControlAdded(AbstractPlugin plugin, PluginControl addedControl)
{
// Handle control added by the plugin and add the new control to the application
}
void plugin_OnControlChanged(AbstractPlugin plugin, PluginControl changedControl)
{
// Handle control changed by the plugin and updates the concerned control in the application
}
void plugin_OnControlRemoved(AbstractPlugin plugin, PluginControl removedControl)
{
// Handle control removed by the plugin and remove the control from the application
}
}

因此,PluginsController 类还必须扩展 MarshalByRefObject 类,因为添加到事件的方法必须通过代理发送。

由于 API 的复杂架构,我还有许多其他问题,并且无法使用某些函数。 如果我在当前域中加载我的插件,一切正常,但程序集版本之间可能存在问题。 我在想我将无法执行我想要的... 因此,我只会确保我的 API 在加载插件之前加载了所有依赖项,如果程序集与插件使用的先前版本不兼容,插件可能无法工作。

如果有人有任何其他建议...

谢谢。

您可以将每个插件放在它自己的应用程序域中,然后将您的 dll 加载到该应用程序域中。有关示例,请参见此处

其他解决方案可能是:

  • 对程序集进行强命名,并将两个版本中的 UsedLibrary 安装到 GAC,但这需要为每个安装完成,我认为您无法控制加载的库
  • 如果 dll 版本兼容,则可以使用程序集重定向来始终使用两个 dll 中较新的版本。

相关内容

  • 没有找到相关文章

最新更新