MEF组合错误未传播内部异常(通过消息除外)

本文关键字:消息 异常 错误 组合 传播 内部 MEF | 更新日期: 2023-09-27 18:29:28

我正在与MEF合作,将来自不同来源的模块加载到我的应用程序中。我有一个例子(下面的代码),我创建了一个可组合的类,它在构造函数中抛出异常。该异常导致组合失败,从而抛出一个异常,说明"为什么"。。。声明中说原因是InvalidCastException。。。这是真的。

如果我打印异常,我知道它为什么失败,但我如何检索抛出的实际原始异常(InvalidCastException),以便在请求所述类的实例的模块中正确处理它——而不仅仅是一个会错过其他异常的通用捕获?查询CompositionException.Errors也不会给我原始的异常。。。

代码:

using System.ComponentModel.Composition;
using Microsoft.Practices.ServiceLocation;
[Export(typeof(A))]
Class A
{
    [ImportingConstructor]
    public A(ISomeinterface x, ISomeOtherInterface y)
    {
        //// Throw some exception (in my code it happens to be an InvalidCastException)
        throw new InvalidCastException ("Unable to cast object of type 'Sometype' to type 'Someothertype'.");  
    }
}
Class B
{
    public B(IServiceLocator serviceLocator)
    {
        try
        {
            //// Here is where the exception would be thrown as an "ActivationException"
            A myAInstance = serviceLocator.GetInstance(A);
        }
        catch (ActivationException activationException)
        {
            //// Print original activation exception from trying to get the service
            System.Diagnostics.Debug.WriteLine(activationException);
            if (ex.InnerException is CompositionException)
            {
                CompositionException compositionException = (CompositionException)activationException.InnerException;
                //// *** Here is where I want to retrieve the InvalidCastException in order to handle it properly
                //// *** Also, componentException.InnerException is "null" and so is the componentException.Errors[0].Exception.InnerException 
            }
            else
            {
                throw;
            }
        }
    }
}

输出:

Microsoft.Practices.ServiceLocation.ActivationException: Activation error occured while trying to get instance of type A, key "" ---> System.ComponentModel.Composition.CompositionException: The composition produced a single composition error. The root cause is provided below. Review the CompositionException.Errors property for more detailed information.
1) Unable to cast object of type 'Sometype' to type 'Someothertype'.
Resulting in: An exception occurred while trying to create an instance of type 'A'.
Resulting in: Cannot activate part 'A'.
Element: A -->  A -->  DirectoryCatalog (Path="C:'path'to'code'")
Resulting in: Cannot get export 'A (ContractName="A")' from part 'A'.
Element: A (ContractName="A") -->  A -->  DirectoryCatalog (Path="C:'path'to'code'")
   at System.ComponentModel.Composition.Hosting.CompositionServices.GetExportedValueFromComposedPart(ImportEngine engine, ComposablePart part, ExportDefinition definition)
   at System.ComponentModel.Composition.Hosting.CatalogExportProvider.GetExportedValue(CatalogPart part, ExportDefinition export, Boolean isSharedPart)
   at System.ComponentModel.Composition.ExportServices.GetCastedExportedValue[T](Export export)
   at System.ComponentModel.Composition.ExportServices.<>c__DisplayClass10`2.<CreateSemiStronglyTypedLazy>b__d()
   at System.Lazy`1.CreateValue()
   at System.Lazy`1.LazyInitValue()
   at Microsoft.Practices.Prism.MefExtensions.MefServiceLocatorAdapter.DoGetInstance(Type serviceType, String key) in c:'release'WorkingDir'PrismLibraryBuild'PrismLibrary'Desktop'Prism.MefExtensions'MefServiceLocatorAdapter.cs:line 73
   at Microsoft.Practices.ServiceLocation.ServiceLocatorImplBase.GetInstance(Type serviceType, String key)
   --- End of inner exception stack trace ---
   at Microsoft.Practices.ServiceLocation.ServiceLocatorImplBase.GetInstance(Type serviceType, String key)
   at Microsoft.Practices.ServiceLocation.ServiceLocatorImplBase.GetInstance[TService]()
   at <code> line whatever...
System.ComponentModel.Composition.CompositionException: The composition produced a single composition error. The root cause is provided below. Review the CompositionException.Errors property for more detailed information.

MEF组合错误未传播内部异常(通过消息除外)

我找到了解决方案,实际异常嵌套在compositionException.Errors层次结构的深处。人们可能会认为原始异常会在原始组合异常下,但实际上这就是访问它的方法:

它恰好是另一个组合异常的一个错误中的内部异常,该异常本身就是原始组合异常中的错误之一

CompositionException compositionException = (CompositionException)activationException.InnerException;
CompositionException innerCompositionException = compositionException.Errors[0].Exception;
InvalidCastException castException = (InvalidCastException)innerCompositionException.Errors[0].Exception.InnerException

我不会删除这个,以防其他人遇到同样的事情。