使用MEF拒绝不良的DLL文件

3
我正在尝试设计一个可扩展的GUI应用程序,利用插件和MEF。现在大部分工作都按计划进行。然而,在某些情况下,我会有一个不符合我设计的契约的坏DLL。我想告诉MEF忽略这个坏的DLL,并保留该目录中的所有其他内容。是否有任何方法可以做到这一点(最好不要删除坏的DLL)?
我已经阅读了一些资料,并注意到调用dirCatalog.Parts.ToArray()将帮助我捕获ReflectionTypeLoadException,在添加早期出现的坏DLL时抛出,以便我有时间处理它(在将其添加到容器之前)。虽然这有助于调试,但我不想因为一个坏的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

最终,这是我的解决方案。虽然不是理想的,但似乎可以工作。我将过滤方法与追加方法连接起来。

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
        }
    }
}

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