2

错误:

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不要尝试导入“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 忽略它并使用不带参数的构造函数,那将是最简单的解决方案。有谁知道该怎么做?

编辑:我可以通过在空构造函数上设置标签来解决它 [ImportingConstructor],但这意味着我也必须在该项目中引用 MEF,我是否可以通过新的 fluent API 使用 RegistrationBuilder 来代替它?

4

2 回答 2

2

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

public MyMefClass([Import(AllowDefault=true)]myNonMefInterface myNonMefClass) {
    _myNonMefClass = myNonMefClass;
}
于 2013-11-15T07:12:00.947 回答
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

于 2013-11-19T04:57:41.963 回答