【问题标题】:Making imports available around your code在您的代码周围提供导入
【发布时间】:2008-10-13 19:17:05
【问题描述】:

在我的MEF 用法中,我有一堆我想在我的代码的许多其他部分中提供的导入。比如:

[Export (typeof (IBarProvider))]
class MyBarFactory : IBarPovider
{
    [Import]
    public IFoo1Service IFoo1Service { get; set; }

    [Import]
    public IFoo2Service IFoo2Service { get; set; }

    [Import]
    public IFoo3Service IFoo3Service { get; set; }

    [Import]
    public IFoo4Service IFoo4Service { get; set; }

    [Import]
    public IFoo5Service IFoo5Service { get; set; }

    public IBar CreateBar()
    {
        return new BarImplementation(/* want to pass the imported services here */);
    }
}

class BarImplementation : IBar
{
    readonly zib zib;

    public BarImplementation(/* ... */)
    {
        this.zib = new Zib(/* pass services here, too */);
    }
}

我可以将每个导入的服务作为单独的参数传递,但这是很多无聊的代码。一定有更好的东西。有什么想法吗?

【问题讨论】:

    标签: c# design-patterns mef


    【解决方案1】:

    我不完全确定这是否能回答您的问题,但您是否考虑过使用构造函数注入?

    class BarImplementation : IBar
    {
        [ImportingConstructor]
        public BarImplementation(IFoo1Service foo1, IFoo2Service foo2, ...) { }
    }
    

    通过使用 ImportingConstructor 属性标记您的构造函数,它实际上会使该构造函数的所有参数都需要导入。

    【讨论】:

      【解决方案2】:

      我想过做一个接口来提供这些服务:

      partial class BarImplementation
      {
          public IRequiredServices
          {
      
              public IFoo1Service IFoo1Service { get; set; }
              public IFoo2Service IFoo2Service { get; set; }  
              public IFoo3Service IFoo3Service { get; set; }          
              public IFoo4Service IFoo4Service { get; set; }      
              public IFoo5Service IFoo5Service { get; set; }
          }
      }
      

      然后MyBarFactory 实现BarImplementation : BarImplementation.IRequiredServices。这很容易写,但是,我如何将它们传递给Zib?我不想以这种方式将Zib 与其消费者耦合。

      【讨论】:

        【解决方案3】:

        我可以使IImports 成为一个包含我导入的所有服务的接口,将其传递到任何地方,然后类可以使用或不使用它们喜欢的任何一个。但这将所有类结合在一起。

        【讨论】:

        • 这基本上是我走的路线。我的所有模块都有一个 IHost 属性,我在加载它们后就设置了它。 IHost 然后可以有一个加载模块的列表...
        猜你喜欢
        • 2015-05-23
        • 1970-01-01
        • 2019-07-30
        • 2021-07-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-02-16
        • 2017-03-18
        相关资源
        最近更新 更多