错误:
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 以某种方式代替?
最佳答案
要在 MEF 中获取可选导入,您应该使用 Optional Imports 。例如在您的代码中:
public MyMefClass([Import(AllowDefault=true)]myNonMefInterface myNonMefClass) {
_myNonMefClass = myNonMefClass;
}
关于c# - MEF 2 - 未找到与具有多个重载的构造函数的约束相匹配的导出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19995313/