我有这样的情况,我想在我正在做的一个国际象棋项目中使用MEF。假设我有一个类构造函数,如下所示:
public class MoveManager
{
private Piece _piece;
public MoveManager(Piece piece)
{
_piece = piece;
}
Mode code here...
}在此上下文中,我将有几个类将从Piece派生,如Pawn、Rook等。如果我将导出属性放在派生自Piece的所有类上,则传递到构造函数的对象为空。MEF循环遍历所有具有[Export(typeof(Piece))]的类,如果它超过1,则传递null。所以我不能以这种方式使用MEF。我将使用Abstact Factory来获取正确的片段。似乎MEF的DI部分只能接受一个带有[Export(typeof(some base class))]的类。
有谁能解释一下这件事吗?
发布于 2015-10-23 01:58:42
我想你可能正在寻找[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
}
}https://stackoverflow.com/questions/3214110
复制相似问题