Handle ReflectionTypeLoadException during MEF composition

前端 未结 3 1986
我寻月下人不归
我寻月下人不归 2020-12-13 14:18

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

3条回答
  •  甜味超标
    2020-12-13 15:07

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

提交回复
热议问题