在运行时加载带有子文件夹引用的程序集 [英] Load assemblies with references from subfolders at runtime

查看:29
本文介绍了在运行时加载带有子文件夹引用的程序集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

  • 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() 创建它.

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

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

public void LoadReferences(Assembly assembly){var loadedReferences = AppDomain.CurrentDomain.GetAssemblies();foreach (AssemblyName 引用在 assembly.GetReferencedAssemblies()){//仅在引用尚未加载时加载if (loadedReferences.FirstOrDefault(a => a.FullName == reference.FullName) == null){//搜索所有子文件夹foreach (在 Directory.GetDirectories(Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location)) 中的变量位置){//GetDirectoriesRecusrive 递归搜索所有子文件夹及其子文件夹//返回找到的所有文件的路径列表foreach(GetDirectoriesRecusrive(位置)中的var dir){var assemblyPath = Directory.GetFiles(dir, "*.dll").FirstOrDefault(f => Path.GetFileName(f) == reference.Name+".dll");如果(程序集路径!= null){Assembly.LoadFile(assemblyPath);休息;//一旦找到 vald .dll,就停止搜索此引用.}}}}}}

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

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

问题:

如何在没有 System.IO.FileNotFoundException 的情况下从一个子文件夹加载程序集及其引用?

附加信息:

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

解决方案

TL;DR;

您正在寻找

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

var plugins = new List();var pluginsPath = Path.Combine(Application.StartupPath, 插件");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();如果(程序集文件!= null)返回 Assembly.LoadFrom(assemblyFile);throw new Exception($"'{name}' Not found");};foreach(插件文件中的var pluginFile){var pluginAssembly = Assembly.LoadFrom(pluginFile);var pluginTypes = pluginAssembly.GetTypes().Where(x => typeof(IPlugin).IsAssignableFrom(x));foreach(pluginTypes 中的 var pluginType){var plugin = (IPlugin)Activator.CreateInstance(pluginType);var button = new Button() { Text = plugin.GetType().Name };按钮.单击 += (obj, arg) =>MessageBox.Show(plugin.SayHello());flowLayoutPanel1.Controls.Add(button);}}

这是结果:

您可以下载或克隆代码:

I am currently working on a project which is supposed to work as a framework for several Add-Ons, which should be loaded at runtime.

I am tasked to have following structure in my application folder:

  • 2 Directories with subfolders. One named "/addons" for Add-Ons and one named "/ref" for any additonal references these addons might use (like System.Windows.Interactivity.dll)
  • When selecting one of the Add-Ons from a menu in the applicaiton, the .dll is supposed to be loaded at runtime and a pre-set entry point should be opened
  • All references of the newly loaded assembly should be loaded aswell.

I know the subfolder and filename when an Add-On is being loaded, so I simply use Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location)) and Path.Combine() to build a path to the .dll and then load it via Assembly.LoadFile() before using reflection with assembly.GetExportedTypes() to find the class that inherits for my 'EntryPointBase' and then create it with Activator.CreateInstance().

However, as soon as I have any references within my Add-On, an System.IO.FileNotFoundException targeting the reference will pop up at assembly.GetExportedTypes()

I built a method to load all referenced assemblies, even made it recursive to load all references from the references, like this:

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.
          }
        }
      }
    }
  }
}

and made sure all references are loaded in by checking AppDomain.CurrentDomain.GetAssemblies(), but the exception stays the same.

It works if either all assemblies are directly in the application folder, or if all references fro the addon are already referenced by the startup application itself. Both ways are not suitable for my case, because higher ups demand on this file system and Add-Ons with new references should be able to load without touching the appication itself.

Question:

How can I load assemblies from one subfolder and their references from another without a System.IO.FileNotFoundException?

Additional information:

  • Application is in the new .csproj format and runs on <TargetFrameworks>netcoreapp3.1;net472</TargetFrameworks>, although support for net472 should be ceased soon (currently still debugging in net472)
  • Most Add-Ons still have the old .csproj format on net472
  • the ref subfolder is sturctured in subfolders aswell (devexpress, system, etc.), while the addon subfolder has no further subfolders.

解决方案

TL;DR;

You are looking for AssemblyResolve event of the AppDomain. If you are loading all the plugin assemblies in the current app domain, then you need to handle the event for AppDomain.CurrentDomain and load the requested assembly in the event handler.

No matter what folder structure you have for references, what you should do is:

  • Get all assembly files form plugins folder
  • Get all assembly files from references folder (entire hierarchy)
  • Handle AssemblyResolve of AppDomain.CurrentDomain and check if the requested assembly name is available files of reference folder, then load and return assembly.
  • For each assembly file in plugins folder, get all types and if the type implements your plugin interface, instantiate it and call its entry point for example.

Example

In this PoC I load all implementations of IPlugin dynamically at run-time from assemblies in Plugins folder and after loading them and resolving all dependencies at run-time, I call SayHello method of plugins.

The application which loads plugins, doesn't have any dependency to plugins and just loads them at run-time from the following folder structure:

This is what I did for loading, resolving and calling the plugins:

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);
    }
}

And this is the result:

You can download or clone the code:

这篇关于在运行时加载带有子文件夹引用的程序集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆