首页 > 解决方案 > C# .net core 条件构造依赖对象

问题描述

我正在创建一个 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-coredesign-patternsdependency-injectionservice-locatorabstract-factory

解决方案


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

public PaymentController(IEnumerable<IPaymentService> services) {}

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

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

示例已经在这里如何在 Asp.Net Core 中注册同一接口的多个实现?

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


推荐阅读