在mef中卸载dll文件

我有一些插件作为DLL文件。 我的应用程序加载DLL并运行正常。 但是当我尝试删除旧插件并用新插件替换它时,它不允许我这样做。 因为它已被应用程序加载。 我发现通过使用appdomain,我们可以做到这一点。 但我无法找到使用mef的解决方案。

我需要一个可以在mef上运行的代码。 下面是我的代码,用于加载插件。

//Creating an instance of aggregate catalog. It aggregates other catalogs var aggregateCatalog = new AggregateCatalog(); //Build the directory path where the parts will be available var directoryPath = "Path to plugins folder"; //Load parts from the available dlls in the specified path using the directory catalog var directoryCatalog = new DirectoryCatalog(directoryPath, "*.dll"); //Add to the aggregate catalog aggregateCatalog.Catalogs.Add(directoryCatalog); //Crete the composition container var container = new CompositionContainer(aggregateCatalog); // Composable parts are created here ie the Import and Export components assembles here container.ComposeParts(this); 

我发现通过使用appdomain,我们可以做到这一点。 但我无法找到使用mef的解决方案。

不幸的是,MEF不支持这一点。 MEF专为应用程序可扩展性而设计,而不是作为支持在运行时卸载和替换代码的通用插件系统。

实现这项工作的唯一方法是在单独的AppDomain中使用MEF,并从整体上卸载AppDomain。 除了卸载打开程序集的整个AppDomain之外,CLR本身不支持卸载已加载的程序集。

如果您尝试在目录上插入一个程序集对象,如下所示:

 Assembly assembly = Assembly.Load(System.IO.File.ReadAllBytes(Path.Combine(directoryPath, ItemPlugin))); aggregateCatalog.Catalogs.Add(new AssemblyCatalog(assembly)); 

您可以稍后删除/更改文件…