简体   繁体   English

如何在 MEF 中动态按需加载插件?

[英]How can plugins be loaded dynamically and on-demand in MEF?

When our application is running, we want it to occasionally poll for new plugins and load them if it finds any.当我们的应用程序运行时,我们希望它偶尔轮询新插件并在找到时加载它们。 We don't just want plugins loaded at startup.我们不只是希望在启动时加载插件。 Is this possible with MEF? MEF可以做到吗? We've done it already with reflection, but MEF gives a nice plugin framework and we would like to use it if possible.我们已经通过反射完成了它,但是 MEF 提供了一个很好的插件框架,如果可能,我们希望使用它。

You can do it using the DirectoryCatalog class that scans all dll assemblies in a folder.您可以使用DirectoryCatalog 类扫描文件夹中的所有 dll 程序集。 It has also a Refresh method that will rescan the directory and refresh the container if changes are found.它还有一个Refresh 方法,如果发现更改,它将重新扫描目录并刷新容器。 This will trigger the ExportsChanged event in the container which contains also information about what changes have occurred.这将触发容器中的ExportsChanged 事件,该事件还包含有关发生了哪些更改的信息。

Here is a very basic sample that demonstrates how to do it:这是一个非常基本的示例,演示了如何执行此操作:

class Program
{
   static void Main(string[] args)
   {
      DirectoryCatalog catalog = new DirectoryCatalog("plugins", "*.dll");
      CompositionContainer container = new CompositionContainer(catalog);
      container.ExportsChanged += Container_ExportsChanged;
      Console.WriteLine("Copy new plugins and press any key to refresh them.");
      Console.ReadKey();
      catalog.Refresh();
      Console.ReadLine();
   }

   private static void Container_ExportsChanged(object sender, ExportsChangeEventArgs e)
   {
      Console.Write("Added Exports: ");
      Console.WriteLine(string.Join(", ", e.AddedExports));
   }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM