MEF重组错误

时间:2013-03-01 11:42:45

标签: export mef

我得到了例外: 1)找到多个匹配约束的导出:     ContractName CompositionTest.C     RequiredTypeIdentity CompositionTest.C

运行程序时

命名空间CompositionTest {

// [Export]  // Also doesn't work
[Export(typeof(C))]
public class C  
{
    //[ImportAttribute(AllowRecomposition = true)]  // also doesn't work
    [Import(AllowRecomposition = true)]
    public C PropertyC { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        // Declare a composition container.
        CompositionContainer compositionContainer = new CompositionContainer();

        compositionContainer.ComposeParts( new C() );  

        compositionContainer.ComposeParts( new C() );  // exception here!
    }
}

}

我做错了什么?

1 个答案:

答案 0 :(得分:2)

第一次调用ComposeParts时,会添加一个新的C对象作为导出到容器。然后第二次调用ComposeParts时,会添加另一个C对象作为导出。这会导致导入问题,因为导入有两个可能的部分,MEF无法做出决定。因此基数例外。

一种解决方案是将导入更改为:

[ImportMany(AllowRecomposition = true)]
public IEnumerable<C> PropertyC { get; set; }

另一种解决方案是在创建容器时实际使用目录。这是使用MEF的常用方法。您可以找到的所有示例都遵循以下方法:

//Create a catalog. In this case, a catalog based on an already loaded assembly.
var catalog = new AssemblyCatalog(typeof(C).Assembly);
//Create a container using the catalog. Only the parts from that catalog will be used.
var compositionContainer = new CompositionContainer(catalog);

有关目录的更多信息,请阅读此article

顺便说一下,我以前从未见过这样一个MEF用法的例子。我的答案主要基于我在调试时所做的观察。