【问题标题】:C# .net core conditional construction of dependency objectsC# .net core 条件构造依赖对象
【发布时间】:2020-02-10 12:07:40
【问题描述】:

我正在创建一个 ASP.NET Core Rest API 应用程序。

在Controller上,根据参数的值我们需要创建请求处理器{处理器的工作是进一步处理请求并执行业务逻辑}。

现在有了 .net core DI,我们如何在系统确定我们需要创建/构造什么类型的对象之前,在运行时数据上执行一些条件时构造对象。

我可以想到 ServiceLocator,但它是反模式。 应该采取什么适当的方法来解决它。

示例代码:

这里我们有一个控制器来计算费用,这个计算取决于请求对象的几个值 (Payment)

现在Payment的值计算逻辑不同,但是两个服务(入站/出站)的参数和返回值都是一样的

public class FeeController : ControllerBase
{

    public PaymentController(IPayemntService is, IPayemntService os)
    {
        _inwordService = is;
        _outwordsService = os;

        // two dependency injected but on a request only need one 
    }

    public ActionResult<int> CalculateFees(Payment payment)
    {
        var retValue = 0;
        // this condition will be more complex...
        if (payment.Direction == PayDirection.Inwords)
        {
            //logic to calculate Fees and Tax for inwords operation
             retValue = _inwordService.calcualte(payment, "some other values may be");
        }
        else
        {
            //logic to calculate Fees and Tax for outwords operation
            retValue = _outwordsService.calcualte(payment, "some other values may be");

        }
        return retValue;
    }
}

通过 .net core DI,我们可以创建两个服务实例,但对于特定请求,只需要其中一个。

【问题讨论】:

    标签: asp.net-core design-patterns dependency-injection service-locator abstract-factory


    【解决方案1】:

    您可以注册多个实现您的接口的类,并将它们作为 IEnumerable 注入构造函数中。

    public PaymentController(IEnumerable<IPaymentService> services) {}
    

    之后,您可以使用 Linq 获取特定实例。将自定义属性添加到您的界面,这将定义您的类型。

    更简洁的方法是编写自己的服务解析器 - 工厂。

    这里已经有示例How to register multiple implementations of the same interface in Asp.Net Core?

    注意,在 service.calculate 上编写条件,我宁愿删除它并调用方法,保持 OOP 多态性处理您的工作,但这取决于您注入的实例。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-27
      • 2016-05-22
      • 1970-01-01
      • 1970-01-01
      • 2018-03-03
      相关资源
      最近更新 更多