有多个构造MEF构造函数的参数 [英] MEF Constructor Parameters with Multiple Constructors

查看:624
本文介绍了有多个构造MEF构造函数的参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开始使用MEF的,我有一个类有多个构造函数,像这样的:

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

[Export(typeof(ifoo))]
class foo : ifoo {
    void foo() { ... }
    [ImportingConstructor]
    void foo(object par1) { ... }
}

我使用 catalog.ComposeExportedValue()作曲时提供的 PAR1 值到第二个构造函数:

I am using catalog.ComposeExportedValue() when composing to supply the par1 value to second constructor:

...
catalog.ComposeExportedValue(par1Value);
catalog.ComposeParts(this);
...

要抱我使用的组件:

[ImportMany(typeof(ifoo))]
public List<Lazy<ifoo, ifoometadata>> FooList { get; set; }

和给我使用的价值属性创建例如, FooList [0] .value的

And to create the foo instance I'm using the value property, FooList[0].Value.

全部的寄托工作正常,除了类的第二个构造函数永远不会被调用。怎么了?

Everthing works fine, except that the second constructor of the foo class is never called. What's wrong?

我如何选择我想要使用的构造函数时MEF实例化类?

How do I select the constructor I want to use when MEF instantiates the class?

推荐答案

MEF应该用你把 ImportingConstructorAttribute 的构造。我不知道发生了什么给你,我无法重现该问题。这是一个测试,显示使用ImportingConstructor上一个类也有一个默认的构造函数:

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

这篇关于有多个构造MEF构造函数的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆