定制MEF

问题描述:

我有这种情况,我想在我正在使用的国际象棋项目中使用MEF。比方说,我有一个类的构造函数,如:定制MEF

public class MoveManager 
{ 
    private Piece _piece; 

    public MoveManager(Piece piece) 
    { 
     _piece = piece; 
    } 
    Mode code here... 
} 

在这方面,我有几个类,会从片一样,典当,鲁克等获得。如果我把所有的派生类出口属性Piece,传入构造函数的对象为null。 MEF遍历所有具有[Export(typeof(Piece))]的类,如果它超过1,它将传入null。所以我不能以这种方式使用MEF。我将使用Abstact Factory来获得正确的作品。似乎MEF的DI部分只能采用一个具有[Export(typeof(some base class))]的类。

任何人都可以对此有所了解吗?

+0

您应该使用[ImportMany(typeof运算(件))]导入导出基本类型'Piece'如果你想要的所有实例规范在出口中使用元数据属性。 – 2016-07-07 21:17:36

我想你可能正在寻找[Importing Constructor] arrtibute,它告诉MEF如何使用导出的类的构造函数。

[Export(typeof(IPiece))] 
class Pawn : IPiece 
{ 
    [ImportingConstructor] 
    public Pawn(ISomeDependency dep, [ImportMany] IEnumerable<IOtherDependency> depList) 
    { 
     //... do stuff with dependencies 
    } 
} 

这需要一个ISomeDependency在其他地方出口(只有一次),并接受任何数目的可能过于出口IOtherDependency的。

假设你每件这样做,然后你可以:

[Export(typeof(IPieceList))] 
class PieceList : IPieceList 
{ 
    [ImportingConstructor] 
    public PieceList([ImportMany] IEnumerable<IPiece> pieces) 
    { 
     // pieces now contains one of each piece that was exported above 
    } 
}