用MEF拒绝坏DLL

时间:2015-01-19 21:37:20

标签: c# dynamic dll plugins mef

我正在尝试使用插件和MEF设计可扩展的GUI应用程序。

现在很多事情似乎按照计划进行。但是,在某些情况下,我会有一个不符合我设计的合同的坏DLL。我希望能够告诉MEF忽略坏DLL并将其他所有内容保存在该目录中。有没有办法做到这一点(最好不删除坏的DLL)?

我已经完成了一些阅读并注意到调用dirCatalog.Parts.ToArray()将帮助我捕获早先添加错误DLL时引发的ReflectionTypeLoadException,以便我有时间处理它(在添加之前)它到容器)。虽然这有助于调试目的,但我不想崩溃我的程序而不是因为一个坏DLL而加载整个目录。

这是我提出的一些(未完成的)代码。

private void appendToCatalog(DirectoryInfo rootDirInfo)
{
    if (rootDirInfo.Exists)
    {
        DirectoryCatalog dirCatalog = new DirectoryCatalog(rootDirInfo.FullName, Constants.Strings.PLUGIN_EXTENSION);

        try
        {
            // detect a problem with the catalog
            dirCatalog.Parts.ToArray();
        }
        catch (ReflectionTypeLoadException ex)
        {
            // try to remove bad plugins
            filterBadPlugins(dirCatalog);
        }

        catalog.Catalogs.Add(dirCatalog);
    }
}

private void filterBadPlugins(DirectoryCatalog dirCatalog)
{
    foreach (var part in dirCatalog.Parts)
    {
        // This should narrow down the problem to a single part
        Type t = part.GetType(); 
        // need to remove the part here somehow
    }
}

1 个答案:

答案 0 :(得分:0)

最终,这是我的解决方案。它并不理想,但似乎有效。我将过滤方法与append方法连接起来。

private void appendToCatalog(DirectoryTreeNode node)
{
    DirectoryInfo info = node.Info;
    FileInfo[] dlls = info.GetFiles("*.dll");

    foreach (FileInfo fileInfo in dlls)
    {
        try
        {
            var ac = new AssemblyCatalog(Assembly.LoadFile(fileInfo.FullName));
            ac.Parts.ToArray(); // throws exception if DLL is bad
            catalog.Catalogs.Add(ac);
        }
        catch
        {
            // some error handling of your choice
        }
    }
}