2010-07-09 16 views
2

我有這種情況,我想在我正在使用的國際象棋項目中使用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

回答

2

我想你可能正在尋找[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 
    } 
}