【发布时间】: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