代码之家  ›  专栏  ›  技术社区  ›  TimothyP

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

  •  11
  • TimothyP  · 技术社区  · 16 年前

    目前,我的WPF应用程序导入了如下部件

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

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

    对于实现ILedPanel的每个类)

    有什么建议吗?

    6 回复  |  直到 16 年前
        1
  •  10
  •   Scott Whitlock    16 年前

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

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

    …然后在以后的代码中。。。

    ILedPanel panel = PanelFactory.BuildPanel();
    
        2
  •  10
  •   Adi Lester    11 年前

    所有其他答案都非常陈旧,所以它们没有提到MEF中一个相对较新的特性,即 ExportFactory . 此泛型类允许您导入 ExportFactory<ILedPanel>

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

    此方法还满足创建零件的所有导入。您可以阅读有关使用的更多信息 出口工厂 here .

        3
  •  8
  •   Wim Coenen    15 年前

    http://blogs.msdn.com/nblumhardt/archive/2008/12/27/container-managed-application-design-prelude-where-does-the-container-belong.aspx

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

    我们正在探索对该场景更直接的支持。

    刻痕

    更新: MEF现在对此有实验支持。看见 this blog post 了解更多信息。

        4
  •  5
  •   Kathleen Kathleen    16 年前

    除非我误解了这个问题,否则它看起来可以通过使用CreationPolicy.NonShared来解决。

        5
  •  3
  •   Bittercoder    16 年前

    查看MEF附带的shapes游戏示例,有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<IShape, IShapeMetadata>[] PossibleShapes { get; set; }
        }
    }
    

    这演示了“按需”创建随机形状实例。。。我认为在您的场景中,您可以在不选择随机实现的情况下执行类似的操作,因为您建议只有一个ILedPanel注册的实现。

        6
  •  2
  •   Luke Schafer    16 年前

    我认为您的意思是希望在这个实例中像服务定位器一样使用MEF,而不是依赖注入容器。尝试查看ValueResolver的示例