MEF Constructor Parameters with Multiple Constructors

后端 未结 2 1557
终归单人心
终归单人心 2021-01-12 07:04

I\'m starting to use MEF, and I have a class with multiple constructors, like this:

[Export(typeof(ifoo))]
class foo : ifoo {
    void foo() { ... }
    [Imp         


        
2条回答
  •  死守一世寂寞
    2021-01-12 07:34

    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(ConstructorParameterContract, ExpectedConstructorParameterValue);
    
            var fooImporter = container.GetExportedValue();
    
            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> FooList { get; set; }
    }
    

提交回复
热议问题