MEF 2 - 未找到与具有多个重载的构造函数的约束匹配的导出

时间:2013-11-15 07:01:21

标签: c# .net mef

错误:

The composition produced a single composition error, with 2 root causes. The root causes are provided below. Review the CompositionException.Errors property for more detailed information.

1) No exports were found that match the constraint: 
    ContractName    MyNonMefInterface
    RequiredTypeIdentity    MyNonMefInterface

Resulting in: Cannot set import 'MyMefClass..ctor (Parameter="myNonMefClass", ContractName="MyNonMefInterface")' on part 'MyMefClass'.

有没有告诉MEF NOT 尝试导入“myInterface”?它是一个可选的参数,如果没有传递给构造函数,它就会被默认:

public MyMefClass() : (new MyNonMefClass()) {}
public MyMefClass(myNonMefInterface myNonMefClass) {
    _myNonMefClass = myNonMefClass;
}

我正在使用MEF 2的新属性配置,并像我这样使用我的RegistrationBuilder:

var builder = new RegistrationBuilder();
builder.ForTypesDerivedFrom<IMyMefClass>().ExportInterfaces();
...
var aggregateCatalog = new AggregateCatalog();

aggregateCatalog.Catalogs.Add(new AssemblyCatalog(typeof(MyMefClass).Assembly, builder));

var container = new CompositionContainer(aggregateCatalog, CompositionOptions.DisableSilentrejection);

基本上我总是在默认构造函数中设置默认的MyNonMefClass,但允许自己重载它以进行测试。它没有为MEF设置并且来自另一个dll,所以如果我可以告诉MEF忽略它并使用没有params的构造函数,那将是最简单的解决方案。有谁知道怎么做?

编辑:我能够通过在空构造函数上设置[ImportingConstructor]标记来解决它,但这意味着我必须在该项目中引用MEF,我是否能够通过新的流利来做到这一点以某种方式使用RegistrationBuilder的API?

2 个答案:

答案 0 :(得分:2)

要在MEF中获取可选导入,您应该使用Optional Imports。例如,在您的代码中:

public MyMefClass([Import(AllowDefault=true)]myNonMefInterface myNonMefClass) {
    _myNonMefClass = myNonMefClass;
}

答案 1 :(得分:0)

好的我找到了答案,有SelectConstructor方法:

builder.ForTypesDerivedFrom<IMyMefClass>().SelectConstructor(ctors =>
{
    var minParams = ctors.Min(ctor => ctor.GetParameters().Length);
    return ctors.First(ctor => ctor.GetParameters().Length == minParams);
}).ExportInterfaces();

这将选择最少量的参数,默认选择最多。希望能帮助别人! :)

http://blogs.msdn.com/b/bclteam/archive/2011/11/01/getting-started-with-convention-based-part-registration-in-mef-version-2.aspx