创建导入的MEF部件的多个实例

目前我的WPF应用程序导入了这样的部分

[Import(typeof(ILedPanel)] public ILedPanel Panel { get; set; } 

但是这给了ma实现ILedPanel的类的单个intance。 我真正想要做的是能够创建我需要的尽可能多的实例。 请注意,在任何给定时间,软件中只包含一个ILedPanel导出。

(如果我使用带有List的导入,为每个实现ILedPanel的类提供一个实例)

有什么建议?

今天在MEF中没有“内置”支持,但在恢复服务定位器之前,您可能会在这里找到一些灵感: http : //blogs.msdn.com/nblumhardt/archive/2008/12/27/container -managed-应用设计前奏-其中此结果的容器-belong.aspx

基本思想是将容器“导入”需要进行动态实例化的组件。

我们正在探索对这种情况的更直接支持。

缺口

更新: MEF现在已经为此提供了实验支持。 有关更多信息,请参阅此博客文章 。

我不确定这是否是Nicolas所指的,但您可以导入Factory类而不是实例类,如下所示:

 [Import(typeof(ILedPanelFactory)] public ILedPanelFactory PanelFactory { get; set; } 

……然后在你的代码中……

 ILedPanel panel = PanelFactory.BuildPanel(); 

所有其他答案都很老,所以他们没有在MEF中提到一个名为ExportFactory的相对较新的function。 这个generics类允许您导入ExportFactory并根据需要创建ExportFactory实例,因此您的代码将如下所示:

 [Import(typeof(ILedPanel)] public ExportFactory PanelFactory { get; set; } public ILedPanel CreateNewLedPanelInstance() { return PanelFactory.CreateExport().Value; } 

此方法还满足创建零件的任何导入。 您可以在此处阅读有关使用ExportFactory类的更多信息。

除非我误解了这个问题,否则看起来只需使用CreationPolicy.NonShared即可解决。

这假定声明Panel的代码存在于您想要的面板的任何位置。 您将在具有此声明(导入)的每个类的每个实例中获得ILedPanel的新实例。

看看MEF附带的形状游戏样本,有ShapeFactory类:

 [Export] public class ShapeFactory { private readonly Random random = new Random((int)DateTime.Now.Ticks); [Import] private ICompositionService CompositionService { get; set; } public IShape GetRandomShape() { var shapeRetriever = new ShapeRetriever(); CompositionService.SatisfyImports(shapeRetriever); int randomIndex = random.Next(shapeRetriever.PossibleShapes.Length); return shapeRetriever.PossibleShapes[randomIndex].GetExportedObject(); } private class ShapeRetriever { [ImportMany(RequiredCreationPolicy = CreationPolicy.NonShared)] public Export[] PossibleShapes { get; set; } } } 

这演示了“按需”创建一个随机形状实例…我认为在你的场景中你可以做一些类似的事情而不选择随机实现,因为你建议只有一个ILedPanel注册实现。

我认为你的意思是你想在这个实例中使用MEF,就像服务定位器而不是dependency injection容器。 尝试查看ValueResolver的示例