导入具有特定参数的类

时间:2011-12-18 08:47:54

标签: wpf mvvm dependency-injection mef

我得到了一个用MEF导出的ViewModel。根据将提供给它的枚举/特定对象参数,我希望每次导入时都会对此ViewModel进行不同的初始化。

我一直在读这个主题,我发现可能是这个 -

http://msdn.microsoft.com/en-us/library/ee155691.aspx#metadata_and_metadata_views

能够满足我的需求,但我不确定这是否是最佳方式。

我一直在考虑的另一种方法是正常导入类,然后一旦我有一个实例,就调用一个特殊的初始化方法来接收我的参数。然而,这似乎不是经典的MEF实现,并且可能会损失它的一些“魔力”。

我希望有人能够为我指出实现这一目标的推荐方法。

谢谢!

1 个答案:

答案 0 :(得分:1)

解决方法是导出创建您的类型实例的工厂。虽然这意味着你无法直接导入thos实例,但它确实有一个好处,即创建它们的逻辑是工厂的责任,因此该类用户不必了解它:

public class ServiceWithParameter
{
  public ServiceWithParameter( int a )
  {
    this.a = a;
  }

  private readonly int a;
}

[Export]
public class ServiceWithParameterFactory
{
  public ServiceWithParameterFactory()
  {
    instance = 0;
  }

  public ServiceWithParameter Instance()
  {
    return new ServiceWithParameter( instance++ );
  }

  private int instance;
}

  //now everywhere you need ServiceWithParameter:
[Import]
ServiceWithParameterFactory serviceFactory;

var instanceA = serviceFactory.Instance(); //instanceA.a = 0
var instanceB = serviceFactory.Instance(); //instanceB.a = 1

更具扩展性的方法是告诉容器您有工厂,并在此处显示示例:http://pwlodek.blogspot.com/2010/10/mef-object-factories-using-export.html