【问题标题】:Unloading a dll file in mef在mef中卸载一个dll文件
【发布时间】:2012-02-29 07:05:39
【问题描述】:

我有一些插件作为 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 i.e. the Import and Export components assembles here
container.ComposeParts(this);

【问题讨论】:

    标签: c# dll mef


    【解决方案1】:

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

    很遗憾,MEF 不支持此功能。 MEF 是专为应用程序可扩展性而设计的,而不是作为支持在运行时卸载和替换代码的通用插件系统。

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

    【讨论】:

    • 应该有解决办法。我听说这将在 mef 下一个版本中出现。不知道是真是假。
    • @fhnaseer 不——至少到目前为止没有公开展示过。这确实超出了 MEF 的预期用例,所以我怀疑它会在那里发生。在 CLR 中删除程序集的唯一受支持的方法是卸载整个 AppDomain。 MEF 作为一个图书馆,无法“解决”这个问题。
    • 那么 ImportMany 中的“AllowRecomposition = true”是什么意思。如果我写与否,行为是相同的。
    • @fhnaseer 它允许 MEF 引入更多程序集 - 但它永远不会删除它们。基本上,IEnumerable 是用额外的 new 类型重新创建的,但旧的程序集仍然加载在内存中。
    【解决方案2】:

    如果您尝试像这样在目录中插入一个装配对象:

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

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

    【讨论】:

    • 您可以从aggregateCatalog 中删除它,但如果不卸载空洞appdomain,您将无法从appdomain 中卸载程序集。
    猜你喜欢
    • 1970-01-01
    • 2016-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-06
    相关资源
    最近更新 更多