【问题标题】:Customizing MEF自定义 MEF
【发布时间】:2010-07-09 15:30:02
【问题描述】:

我有这种情况,我想在我正在从事的国际象棋项目中使用 MEF。假设我有一个类构造函数,如下所示:

public class MoveManager
{
   private Piece _piece;

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

在这种情况下,我将有几个派生自 Piece 的类,例如 Pawn、Rook 等。如果我将导出属性放在派生自 Piece 的所有类上,则传递给构造函数的对象为 null。 MEF 循环遍历所有具有[Export(typeof(Piece))] 的类,如果超过 1,则传入 null。所以我不能以这种方式使用 MEF。我将使用抽象工厂来获得正确的作品。似乎 MEF 的 DI 部分只能采用具有 [Export(typeof(some base class))] 的单个类。

有人能解释一下吗?

【问题讨论】:

  • 你应该使用 [ImportMany(typeof(Piece))] 来导入所有导出基本类型 Piece 的实例,如果你想在导出中使用元数据属性的一些规范。

标签: model-view-controller mef


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多