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
我还没有解决的办法,只是需要做进一步的研究。
发布于 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中的类型指向在程序集中定义的真实类型。
因此,我上面的代码必须如下所示才能正常工作:
var test2 = container.GetExports(t.UnderlyingSystemType, null, null).First().Value;https://stackoverflow.com/questions/24051835
复制相似问题