在 MEF 组合期间处理 ReflectionTypeLoadException

发布于 2024-10-01 04:52:07 字数 260 浏览 1 评论 0原文

我在 MEF 中使用 DirectoryCatalog 来满足应用程序中的导入。但是,当我尝试编写目录时,目录中有时会出现混淆的程序集,导致出现 ReflectionTypeLoadException

我知道我可以通过使用单独的目录或使用 DirectoryCatalog 上的搜索过滤器来解决这个问题,但我想要一种更通用的方法来解决问题。有什么方法可以处理异常并允许组合继续吗?或者还有其他更通用的解决方案?

I am using a DirectoryCatalog in MEF to satisfy imports in my application. However, there are sometimes obfuscated assemblies in the directory that cause a ReflectionTypeLoadException when I try to compose the catalog.

I know I can get round it by using a separate directory or by using a search filter on the DirectoryCatalog but I want a more general way to solve the problem. Is there some way I can handle the exception and allow composition to continue? Or is there another more general solution?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

音盲 2024-10-08 04:52:07

为了避免其他人编写自己的 SafeDirectoryCatalog 实现,这是我根据 Wim Coenen 的建议提出的实现:

public class SafeDirectoryCatalog : ComposablePartCatalog
{
    private readonly AggregateCatalog _catalog;

    public SafeDirectoryCatalog(string directory)
    {
        var files = Directory.EnumerateFiles(directory, "*.dll", SearchOption.AllDirectories);

        _catalog = new AggregateCatalog();

        foreach (var file in files)
        {
            try
            {
                var asmCat = new AssemblyCatalog(file);

                //Force MEF to load the plugin and figure out if there are any exports
                // good assemblies will not throw the RTLE exception and can be added to the catalog
                if (asmCat.Parts.ToList().Count > 0)
                    _catalog.Catalogs.Add(asmCat);
            }
            catch (ReflectionTypeLoadException)
            {
            }
            catch (BadImageFormatException)
            {
            }
        }
    }
    public override IQueryable<ComposablePartDefinition> Parts
    {
        get { return _catalog.Parts; }
    }
}

To save others from writing their own implementation of the SafeDirectoryCatalog, here is the one I came up with based upon Wim Coenen's suggestions:

public class SafeDirectoryCatalog : ComposablePartCatalog
{
    private readonly AggregateCatalog _catalog;

    public SafeDirectoryCatalog(string directory)
    {
        var files = Directory.EnumerateFiles(directory, "*.dll", SearchOption.AllDirectories);

        _catalog = new AggregateCatalog();

        foreach (var file in files)
        {
            try
            {
                var asmCat = new AssemblyCatalog(file);

                //Force MEF to load the plugin and figure out if there are any exports
                // good assemblies will not throw the RTLE exception and can be added to the catalog
                if (asmCat.Parts.ToList().Count > 0)
                    _catalog.Catalogs.Add(asmCat);
            }
            catch (ReflectionTypeLoadException)
            {
            }
            catch (BadImageFormatException)
            {
            }
        }
    }
    public override IQueryable<ComposablePartDefinition> Parts
    {
        get { return _catalog.Parts; }
    }
}
林空鹿饮溪 2024-10-08 04:52:07

DirectoryCatalog 已经具有捕获 ReflectionTypeLoadException 并忽略这些程序集的代码。不幸的是,正如我报告的,仅仅创建AssemblyCatalog还不能触发异常,使代码不起作用。

该异常实际上是由第一次调用 AssemblyCatalog.Parts 触发的。

您必须自己执行此操作,而不是使用 MEF 中的 DirectoryCatalog

  • 扫描目录中的程序集,
  • 加载每个程序集并为其
  • 调用 AssemblyCatalog 创建一个 AssemblyCatalog。 Parts.ToArray() 强制异常,并捕获它
  • 用 AggregateCatalog 聚合所有好的目录

DirectoryCatalog already has code to catch ReflectionTypeLoadException and ignore those assemblies. Unfortunately, as I have reported, merely creating the AssemblyCatalog will not yet trigger the exception so that code doesn't work.

The exception is actually triggered by the first call to AssemblyCatalog.Parts.

Instead of using the DirectoryCatalog from MEF, you will have to do it yourself:

  • scan a directory for assemblies
  • load each assembly and creates a AssemblyCatalog for it
  • invoke AssemblyCatalog.Parts.ToArray() to force the exception, and catch it
  • aggregate all the good catalogs with a AggregateCatalog
英雄似剑 2024-10-08 04:52:07

我是通过我正在编写的 API 执行此操作的,并且 SafeDirectoryCatalog 不会记录与来自不同程序集的单个导入匹配的多个导出。 MEF 调试通常通过调试器和 TraceListener 完成。我已经使用了 Log4Net,并且我不希望有人需要在配置文件中添加另一个条目只是为了支持日志记录。 http ://blogs.msdn.com/b/dsplaisted/archive/2010/07/13/how-to-debug-and-diagnose-mef-failures.aspx我想出了:

    // I don't want people to have to add configuration information to get this logging. 
    // I know this brittle, but don't judge... please. It makes consuing the api so much
    // easier.
    private static void EnsureLog4NetListener()
    {
        try
        {
            Assembly compositionAssembly = Assembly.GetAssembly(typeof (CompositionContainer));
            Type compSource = compositionAssembly.GetType("System.ComponentModel.Composition.Diagnostics.CompositionTraceSource");

            PropertyInfo canWriteErrorProp = compSource.GetProperty("CanWriteError");
            canWriteErrorProp.GetGetMethod().Invoke(null,
                                                    BindingFlags.Public | BindingFlags.NonPublic |
                                                    BindingFlags.Static, null, null,
                                                    null);

            Type traceSourceTraceWriterType =
                compositionAssembly.GetType(
                    "System.ComponentModel.Composition.Diagnostics.TraceSourceTraceWriter");

            TraceSource traceSource = (TraceSource)traceSourceTraceWriterType.GetField("Source",
                                                                          BindingFlags.Public |
                                                                          BindingFlags.NonPublic |
                                                                          BindingFlags.Static).GetValue(null);

            traceSource.Listeners.Add(new Log4NetTraceListener(logger));                
        }
        catch (Exception e)
        {
            logger.Value.Error("Cannot hook MEF compisition listener. Composition errors may be swallowed.", e);
        }
    }  

I was doing this from an API I was writing and the SafeDirectoryCatalog would not log multiple exports matching a single import from different assemblies. MEF debugging is typically done via debugger and TraceListener. I already used Log4Net and I didn't want someone to need to add another entry to the config file just to support logging. http://blogs.msdn.com/b/dsplaisted/archive/2010/07/13/how-to-debug-and-diagnose-mef-failures.aspx I came up with:

    // I don't want people to have to add configuration information to get this logging. 
    // I know this brittle, but don't judge... please. It makes consuing the api so much
    // easier.
    private static void EnsureLog4NetListener()
    {
        try
        {
            Assembly compositionAssembly = Assembly.GetAssembly(typeof (CompositionContainer));
            Type compSource = compositionAssembly.GetType("System.ComponentModel.Composition.Diagnostics.CompositionTraceSource");

            PropertyInfo canWriteErrorProp = compSource.GetProperty("CanWriteError");
            canWriteErrorProp.GetGetMethod().Invoke(null,
                                                    BindingFlags.Public | BindingFlags.NonPublic |
                                                    BindingFlags.Static, null, null,
                                                    null);

            Type traceSourceTraceWriterType =
                compositionAssembly.GetType(
                    "System.ComponentModel.Composition.Diagnostics.TraceSourceTraceWriter");

            TraceSource traceSource = (TraceSource)traceSourceTraceWriterType.GetField("Source",
                                                                          BindingFlags.Public |
                                                                          BindingFlags.NonPublic |
                                                                          BindingFlags.Static).GetValue(null);

            traceSource.Listeners.Add(new Log4NetTraceListener(logger));                
        }
        catch (Exception e)
        {
            logger.Value.Error("Cannot hook MEF compisition listener. Composition errors may be swallowed.", e);
        }
    }  
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文