【问题标题】:Rejecting bad DLL's with MEF使用 MEF 拒绝坏 DLL
【发布时间】:2015-01-19 21:37:20
【问题描述】:

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

现在大部分似乎都在按计划进行。但是,在某些情况下,我会得到一个不符合我设计的合同的坏 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
    }
}

【问题讨论】:

    标签: c# dynamic dll plugins mef


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-03-16
      • 1970-01-01
      • 2012-10-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多