MEF Constructor Parameters with Multiple Constructors

守給你的承諾、 提交于 2019-12-01 04:15:24

MEF should use the constructor you put the ImportingConstructorAttribute on. I'm not sure what is happening for you, I wasn't able to reproduce the issue. Here is a test which shows using an ImportingConstructor on a class that also has a default constructor:

[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; }
}

Are you passing an instance of the foo class into the ComposeExportedValue method? In that case the object has already been constructed and the constructor can't be called again, so MEF will ignore the constructor imports.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!