在运行时加载带有子文件夹引用的程序集

Azz*_*rel 4 .net c# reflection .net-assembly .net-core

我目前正在开发一个项目,该项目应该作为多个附加组件的框架工作,这些附加组件应该在运行时加载。

我的任务是在我的应用程序文件夹中具有以下结构:

  • 2 带有子文件夹的目录。一个名为“ /addons ”的附加组件和一个名为“ /ref ”的用于这些插件可能使用的任何附加引用(如System.Windows.Interactivity.dll
  • 当从应用程序的菜单中选择一个附加组件时,.dll 应该在运行时加载,并且应该打开一个预设的入口点
  • 新加载的程序集的所有引用也应加载。

我知道加载附加组件时的子文件夹和文件名,因此我只需使用Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location))Path.Combine()构建 .dll 的路径,然后Assembly.LoadFile()在使用反射之前加载它assembly.GetExportedTypes()以找到为我的“EntryPointBase”继承的类,然后用Activator.CreateInstance().

但是,只要我的附加组件中有任何引用System.IO.FileNotFoundException就会弹出一个针对该引用的目标assembly.GetExportedTypes()

我构建了一个方法来加载所有引用的程序集,甚至递归地从引用加载所有引用,如下所示:

public void LoadReferences(Assembly assembly)
{

  var loadedReferences = AppDomain.CurrentDomain.GetAssemblies();

  foreach (AssemblyName reference in assembly.GetReferencedAssemblies())
  {
    //only load when the reference has not already been loaded 
    if (loadedReferences.FirstOrDefault(a => a.FullName == reference.FullName) == null)
    {
      //search in all subfolders
      foreach (var location in Directory.GetDirectories(Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location)))
      {
        //GetDirectoriesRecusrive searchs all subfolders and their subfolders recursive and 
        //returns a list of paths for all files found
        foreach (var dir in GetDirectoriesRecusrive(location))
        {

          var assemblyPath = Directory.GetFiles(dir, "*.dll").FirstOrDefault(f => Path.GetFileName(f) == reference.Name+".dll");
          if (assemblyPath != null)
          {
            Assembly.LoadFile(assemblyPath); 
            break; //as soon as you find a vald .dll, stop the search for this reference.
          }
        }
      }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

并确保通过检查加载所有引用AppDomain.CurrentDomain.GetAssemblies(),但异常保持不变。

如果所有程序集都直接位于应用程序文件夹中,或者来自插件的所有引用都已被启动应用程序本身引用,则它会起作用。这两种方式都不适合我的情况,因为对这个文件系统的更高需求和带有新引用的附加组件应该能够在不接触应用程序本身的情况下加载。

题:

如何在没有System.IO.FileNotFoundException.

附加信息:

  • 应用程序在新的.csproj格式上运行<TargetFrameworks>netcoreapp3.1;net472</TargetFrameworks>,虽然net472支持应尽快停止(目前仍处于调试net472)
  • 大多数附加组件在 net472 上仍然具有旧的 .csproj 格式
  • ref 子文件夹也包含在子文件夹中(devexpress、system 等),而 addon 子文件夹没有其他子文件夹。

Rez*_*aei 6

TL; 博士;

您正在寻找AssemblyResolve的事件AppDomain。如果要加载当前应用程序域中的所有插件程序集,则需要处理事件AppDomain.CurrentDomain并在事件处理程序中加载请求的程序集。

无论您有什么文件夹结构供参考,您应该做的是:

  • 从插件文件夹中获取所有程序集文件
  • 从引用文件夹(整个层次结构)中获取所有装配文件
  • 手柄AssemblyResolveAppDomain.CurrentDomain,并检查请求的组件名称为参考文件夹的可用文件,然后加载并返回装配。
  • 对于 plugins 文件夹中的每个程序集文件,获取所有类型,如果该类型实现了您的插件接口,则实例化它并调用其入口点,例如。

例子

在这个 PoC 中,我IPlugin在运行时从Plugins文件夹中的程序集动态加载所有实现,在加载它们并在运行时解决所有依赖项后,我调用SayHello插件的方法。

加载插件的应用程序对插件没有任何依赖,只是在运行时从以下文件夹结构加载它们:

在此处输入图片说明

这是我为加载、解析和调用插件所做的:

var plugins = new List<IPlugin>();
var pluginsPath = Path.Combine(Application.StartupPath, "Plugins");
var referencesPath = Path.Combine(Application.StartupPath, "References");

var pluginFiles = Directory.GetFiles(pluginsPath, "*.dll", 
    SearchOption.AllDirectories);
var referenceFiles = Directory.GetFiles(referencesPath, "*.dll", 
    SearchOption.AllDirectories);

AppDomain.CurrentDomain.AssemblyResolve += (obj, arg) =>
{
    var name = $"{new AssemblyName(arg.Name).Name}.dll";
    var assemblyFile = referenceFiles.Where(x => x.EndsWith(name))
        .FirstOrDefault();
    if (assemblyFile != null)
        return Assembly.LoadFrom(assemblyFile);
    throw new Exception($"'{name}' Not found");
};

foreach (var pluginFile in pluginFiles)
{
    var pluginAssembly = Assembly.LoadFrom(pluginFile);
    var pluginTypes = pluginAssembly.GetTypes()
        .Where(x => typeof(IPlugin).IsAssignableFrom(x));
    foreach (var pluginType in pluginTypes)
    {
        var plugin = (IPlugin)Activator.CreateInstance(pluginType);
        var button = new Button() { Text = plugin.GetType().Name };
        button.Click += (obj, arg) => MessageBox.Show(plugin.SayHello());
        flowLayoutPanel1.Controls.Add(button);
    }
}
Run Code Online (Sandbox Code Playgroud)

这是结果:

在此处输入图片说明

您可以下载或克隆代码: