【问题标题】:Factory with Autofac dependencies具有 Autofac 依赖项的工厂
【发布时间】:2017-10-05 13:29:11
【问题描述】:

我想写一个工厂来创建各种类型的“xxNotification”类。我的具体“xxNotification”具有向 AutoFac 注册的依赖项。我想使用 Autofac 获取/解析“xxNotification”的实例。该怎么做?

public interface INotification
{
    void Notify(string Action, int OrderID);
}

public class MagentoOrderStateNotification : INotification
{
    private readonly GenericRepository<Order> _orderRepository;
    private readonly OMRestIntegrationService _oMRestIntegrationService;

    public MagentoOrderStateNotification(GenericRepository<Order> orderRepository, OMRestIntegrationService oMRestIntegrationService)
    {
        _orderRepository = orderRepository;
        _oMRestIntegrationService = oMRestIntegrationService;
    }

    public void Notify(string Action, int OrderID)
    {
        //implementation...
    }
}

public class NotificationFactory
{
    public INotification GetNotification(string NotificationName)
    {
        switch (NotificationName)
        {
            case "MagentoOrderStateNotification":
                //resolve instance of MagentoOrderStateNotification
        }
    }
}

【问题讨论】:

  • 通常,您不会从 DI 容器中“获取”对象。那是被称为服务定位器的反模式。相反,应用程序是在启动时组成的,包括工厂及其依赖项。它被称为Hollywood principle: Don't call us, we'll call you。
  • 好的,那么如果我需要在运行时基于一些配置来实例化一个服务,比如“对于这个订单状态,调用那个和那个 INotification”?
  • 您可以通过方法参数将运行时订单状态传递给您的服务。在您的服务中,您可以使用creational object patten、strategy pattern 或just use generics 来选择要使用的服务。你也可以combine patterns视情况而定。

标签: c# dependency-injection autofac factory-pattern


【解决方案1】:

这看起来很适合 Strategy Pattern。

接口

public interface INotification
{
    void Notify(string Action, int OrderID);
    bool AppliesTo(string NotificationName);
}

public interface INotificationStrategy
{
    void Notify(string NotificationName, string Action, int OrderID);
}

INotification 实现

public class MagentoOrderStateNotification : INotification
{
    private readonly GenericRepository<Order> _orderRepository;
    private readonly OMRestIntegrationService _oMRestIntegrationService;

    public MagentoOrderStateNotification(GenericRepository<Order> orderRepository, OMRestIntegrationService oMRestIntegrationService)
    {
        _orderRepository = orderRepository;
        _oMRestIntegrationService = oMRestIntegrationService;
    }

    public void Notify(string Action, int OrderID)
    {
        //implementation...
    }

    public bool AppliesTo(string NotificationName)
    {
        // Note that you can make the criteria to use this
        // service as advanced as you need to. You could even
        // design your strategy to use multiple services in specific
        // scenarios. But putting that logic here has many advantages
        // over a switch case statement.
        return NotificationName == "a";
    }
}

public class FooOrderStateNotification : INotification
{
    public void Notify(string Action, int OrderID)
    {
        //implementation...
    }

    public bool AppliesTo(string NotificationName)
    {
        return NotificationName == "b";
    }
}

策略

public class NotificationStrategy : INotificationStrategy
{
    private readonly IEnumerable<INotification> oNotifications;

    public MessageStrategy(IEnumerable<INotification> oNotifications)
    {
        if (oNotifications == null)
            throw new ArgumentNullException("oNotifications");
        this.oNotifications = oNotifications;
    }

    public void Notify(string NotificationName, string Action, int OrderID)
    {
        var notification = this.oNotifications
            .FirstOrDefault(x => x.AppliesTo(NotificationName));

        // Possible alternative: get multiple implementations and
        // then loop through them, executing each one.
        // var notifications = this.oNotifications
        //     .Where(x => x.AppliesTo(NotificationName)).ToArray();

        if (notification == null)
        {
            throw new Exception("No notification type registered for " + NotificationName);
        }

        notification.Notify(Action, OrderID);
    }
}

用法

public class SomeService : ISomeService
{
    private readonly INotificationStrategy oNotificationStrategy;

    public SomeService(INotificationStrategy oNotificationStrategy)
    {
        if (oNotificationStrategy == null)
            throw new ArgumentNullException("oNotificationStrategy");
        this.oNotificationStrategy = oNotificationStrategy;
    }

    public void DoSomething()
    {
        this.oNotificationStrategy.Notify("a", "Hello", 1234);
    }
}

请注意,另一种方法可能是使用一些基于 OrderID 的“OrderType”状态来查找要使用的服务(不确定将 OrderID 传递给 Notify() 方法是否真的有意义)。但是无论你怎么切,这是一个应用程序设计问题,而不是 DI 问题。

Autofac 注册

有a few ways,你可以配置Autofac来注册同一个接口的多个实现,以便在NotificationStrategy构造函数中使用。以下是几个例子:

扫描

// Note you may need more than one registration if you are spanning
// multiple assemblies.
builder.RegisterAssemblyTypes(typeof(INotification).Assembly)
   .Where(x => typeof(INotification).IsAssignableFrom(x))
   .AsImplementedInterfaces();

当以这种方式注册实现时,Autofac 会隐式地将所有实现注入到任何IEnumerable&lt;INotification&gt; 构造函数参数中。

樱桃采摘

builder.Register<MagentoOrderStateNotification>()
    .Named<INotification>("magentoOrderStateNotification");
builder.Register<FooOrderStateNotification>()
    .Named<INotification>("fooOrderStateNotification");

builder.RegisterType<NotificationStrategy>()
            .As<INotificationStrategy>()
            .WithParameter(
                (p, c) => p.Name == "oNotifications",
                (p, c) => new[]
                    {
                        c.ResolveNamed<INotification>("magentoOrderStateNotification"),
                        c.ResolveNamed<INotification>("fooOrderStateNotification")
                    });

【讨论】:

  • NotificationStrategy 如何获取 INotification[] oNotifications 作为构造函数参数?
  • 我更新了答案。请注意,要在 Autofac 中进行扫描,需要将 NotificationStrategy 构造函数更改为 IEnumerable&lt;INotification&gt; 而不是 INotification[]。
  • 如果我只希望基于某些运行时条件(例如指定给 CliFx 等 CLI 框架的子命令)注册其中一个策略实现怎么办?从组合根很难知道应该创建哪个具体实现
  • @void.pointer - 这就是AppliesTo 方法的用途。在启动时注册所有策略实例,然后通过将过滤器逻辑放入 AppliesTo 方法中选择一个或多个实例在运行时使用。由于总是加载所有实例,因此通常最好将对象的数量限制在几百个,之后使用抽象工厂可能会更好。
  • 所以基本上就我而言,您认为做builder.Register(c =&gt; c.Resolve&lt;IEnumerable&lt;ICommand&gt;&gt;().First(cmd =&gt; cmd.IsActive)).As&lt;ICommand&gt;() 之类的事情是非滥用的?然后在构造函数中我可以做public MyObject(ICommand cmd) 并在命令行获取用户选择的命令?到目前为止,我一直在使用IActiveCommandProvider,但你的想法更清晰。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多