MEF用4.5约定api打开泛型问题

时间:2014-05-28 04:52:35

标签: generics mef convention

.NET Framework 4.5中的MEF支持泛型类型导出,它以属性方式工作:

[InheritedExport(typeof(Interface1<>))]
public interface Interface1<T>
{

}

public class Type1 : Interface1<string>
{

}

可以解析导出对象:

AssemblyCatalog cat = new AssemblyCatalog(typeof(Program).Assembly, builder);
CompositionContainer container = new CompositionContainer(cat);

var o = container.GetExportedValue<Interface1<string>>();

但为什么它不起作用使用约定基础API:

RegistrationBuilder builder = new RegistrationBuilder();

builder.ForType<Type1>().Export(it => it.AsContractType(typeof(Interface1<>)).Inherited());

谢谢!

1 个答案:

答案 0 :(得分:0)

您希望容器通过它的界面创建对象。但是你正在为特定类型制定规则:

builder.ForType<Type1>()

如果你想这样做,那就有用了:

container.GetExportedValue<Type1>();

您需要做的是为此通用接口创建规则:

    builder.ForTypesMatching(t =>
        {
            return t.GetInterfaces().Any(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(Interface1<>));
        })
        .ExportInterfaces();