MEF 2 GetExports()因奇怪错误而失败

时间:2014-06-05 04:49:10

标签: c# mef

using System;
using System.ComponentModel.Composition.Hosting;
using System.ComponentModel.Composition.ReflectionModel;
using System.ComponentModel.Composition.Registration;
using System.Linq;
using System.Reflection;

namespace MefTest
{
    public interface ITest {}

    public class TestObj : ITest {}

    class Program
    {
        static void Main(string[] args)
        {
            RegistrationBuilder rb = new RegistrationBuilder();

            //Register the class
            rb.ForType<TestObj>().Export();

            var container = new CompositionContainer(new AssemblyCatalog(Assembly.GetExecutingAssembly(), rb));

            //get the type of the first part (there is only 1), which is TestObj
            Type t = ReflectionModelServices.GetPartType(container.Catalog.Parts.First()).Value;

            Type t2 = typeof(TestObj);

            if (t.Equals(t2)) //They look the same in the debugger??
            {
                //This works
                var test1 = container.GetExports(t2, null, null).FirstOrDefault().Value;

                //Fails with ArgumentException: MethodInfo must be a runtime MethodInfo object.
                var test2 = container.GetExports(t, null, null).First().Value;
            }

        }
    }
}

我创建了上面的例子来演示我遇到的问题。 _container.GetExports(t2 ...)我硬编码的类型工作。 但是当我使用linq查询从_container.Catalog.Parts查找类型时,它会失败,并显示一条神秘的错误消息。

任何人都可以给我一个提示,我做错了什么?。

修改:简化了测试用例

修改: 我发现问题,t和t2不完全一样。 t2是System.RuntimeType,t是System.Reflection.Context.Custom.CustomType

我还没有解决方案,但需要进一步研究。

1 个答案:

答案 0 :(得分:2)

我解决了自己的问题:

因此在.Net 4.5中有一个名为CustomReflectionContext的新功能,Ian Griffiths在此解释:.NET 4.5 CustomReflectionContext: what is it useful for?

简而言之,RegistrationBuilder是一个CustomReflectionContext,因此MEF使用的类型是&#34;虚拟化&#34; types(System.Reflection.Context.Custom.CustomType),而不是程序集中实际定义的类型(System.RuntimeType)。 当涉及对象的实例化时,这会导致问题。

解决方案是使用Type对象的UnderlyingSystemType属性。该类型中的哪些点存在于ReflectionContext中,而是组件中定义的实际点。

所以上面的代码必须看起来像这样才能正常工作:

var test2 = container.GetExports(t.UnderlyingSystemType, null, null).First().Value;
相关问题