使用MEF(托管可扩展性框架)从目录加载dll的方法

3

我目前正在使用MEF并遇到一些问题

我想要从目录中加载dlls。

首先,我扫描目录并将两个内容保存在字典中:

来自各自DLL的Name属性(作为字符串)

和模块名称(作为字符串)

这是ScanDirectory()代码

private void ScanPluginDirectory()
{
    catalog = new AggregateCatalog();

    catalog.Catalogs.Add(new DirectoryCatalog(@"..\..\plugin"));            
    container = new CompositionContainer(catalog);

    batch = new CompositionBatch();
    batch.AddPart(this);        

    container.Compose(batch);    

    pluginDictionary = new Dictionary<String, String>();
    foreach (IFilter filter in filters)
    {
        Type t = filter.GetType();
        pluginDictionary.Add(filter.Name, t.Module.Name);
    }
}

当选择复选框中的dll时,显示它们的名称。

我有一个导入语句:

[Import]
public IEnumerable<IFilter> filters { get; set; }

目前我的程序运行良好。我的做法是当我从复选框列表中勾选插件时,将其移动到“已加载”目录中,然后QueryPlugin()方法会在“已加载”目录中查找插件。

当我取消复选框列表中的插件时,我会将其移出“已加载”目录...

我想使用batch.RemovePart()方法来摆脱这种快速将dll从一个目录移动到另一个目录的方式....

注意:我不是手动使用batch添加插件的。

batch.AddPart(new DemoFilter1());

我使用了DirectoryCatalog()代替此方法。

1个回答

3

不要使用DirectoryCatalog,而是使用AggregateCatalog,并为目录中的每个程序集添加一个AssemblyCatalog到AggregateCatalog中。然后当检查或取消选中插件时,您可以将相应的AssemblyCatalog添加或从AggregateCatalog中删除。

请注意,如果在给定的程序集中有多个插件,则此方法可能会出现问题。更健壮的方法可能是使用过滤器来筛选单个部分定义,使用filtered catalog


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接