首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Mef2 GetExports()出现奇怪错误失败

Mef2 GetExports()出现奇怪错误失败
EN

Stack Overflow用户
提问于 2014-06-05 04:49:09
回答 1查看 595关注 0票数 0
代码语言:javascript
复制
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

我还没有解决的办法,只是需要做进一步的研究。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-06-06 02:18:03

我解决了我自己的问题:

因此,在.Net 4.5中有一个名为CustomReflectionContext的新特性,Ian在这里解释说:.NET 4.5 CustomReflectionContext: what is it useful for?

简而言之,RegistrationBuilder是一个CustomReflectionContext,所以MEF使用的类型是“虚拟化”类型(System.Reflection.Context.Custom.CustomType),而不是实际在程序集(System.RuntimeType)中定义的类型。当涉及到对象的实例化时,就会产生问题。

解决方案是使用Type对象的UnderlyingSystemType属性。它从位于ReflectionContext中的类型指向在程序集中定义的真实类型。

因此,我上面的代码必须如下所示才能正常工作:

代码语言:javascript
复制
var test2 = container.GetExports(t.UnderlyingSystemType, null, null).First().Value;
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/24051835

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档