Int*_*WAS 8 .net c# mef multiple-constructors
我开始使用MEF,我有一个包含多个构造函数的类,如下所示:
[Export(typeof(ifoo))]
class foo : ifoo {
void foo() { ... }
[ImportingConstructor]
void foo(object par1) { ... }
}
Run Code Online (Sandbox Code Playgroud)
我catalog.ComposeExportedValue()在编写时使用它来par1
为第二个构造函数提供值:
...
catalog.ComposeExportedValue(par1Value);
catalog.ComposeParts(this);
...
Run Code Online (Sandbox Code Playgroud)
要保存我正在使用的组件:
[ImportMany(typeof(ifoo))]
public List<Lazy<ifoo, ifoometadata>> FooList { get; set; }
Run Code Online (Sandbox Code Playgroud)
为了创建foo我正在使用value属性的实例,FooList[0].Value.
Everthing工作正常,但从foo不调用类的第二个构造函数.怎么了?
当MEF实例化类时,如何选择我想要使用的构造函数?
MEF应该使用你ImportingConstructorAttribute打开的构造函数.我不确定你发生了什么,我无法重现这个问题.这是一个测试,它显示了在具有默认构造函数的类上使用ImportingConstructor:
[TestClass]
public class MefTest
{
public const string ConstructorParameterContract = "FooConstructorParameterContract";
[TestMethod]
public void TestConstructorInjectionWithMultipleConstructors()
{
string ExpectedConstructorParameterValue = "42";
var catalog = new TypeCatalog(typeof(Foo), typeof(FooImporter));
var container = new CompositionContainer(catalog);
container.ComposeExportedValue<string>(ConstructorParameterContract, ExpectedConstructorParameterValue);
var fooImporter = container.GetExportedValue<FooImporter>();
Assert.AreEqual(1, fooImporter.FooList.Count, "Expect a single IFoo import in the list");
Assert.AreEqual(ExpectedConstructorParameterValue, fooImporter.FooList[0].Value.ConstructorParameter, "Expected foo's ConstructorParameter to have the correct value.");
}
}
public interface IFoo
{
string ConstructorParameter { get; }
}
[Export(typeof(IFoo))]
public class Foo : IFoo
{
public Foo()
{
ConstructorParameter = null;
}
[ImportingConstructor]
public Foo([Import(MefTest.ConstructorParameterContract)]string constructorParameter)
{
this.ConstructorParameter = constructorParameter;
}
public string ConstructorParameter { get; private set; }
}
[Export]
public class FooImporter
{
[ImportMany]
public List<Lazy<IFoo>> FooList { get; set; }
}
Run Code Online (Sandbox Code Playgroud)