【发布时间】:2019-09-02 14:01:54
【问题描述】:
我有两个类PaymentGatewayFoo、PaymentGatewayBoo,它们都实现了IPaymentGateway的公共接口:
interface IPaymentGateway { }
class PaymentGatewayFoo : IPaymentGateway { }
class PaymentGatewayBoo : IPaymentGateway { }
客户端请求有一个标识符,该标识符决定使用哪个实现:
public class OrderService
{
private readonly IPaymentGateway _service;
public void DoOrder(bool isFoo)
{
if (isFoo)
//this._service should be resolved with PaymentGatewayFoo
else
//this._service should be resolved with PaymentGatewayBoo
this._service.Pay();
}
}
如何根据客户在运行时的请求解决正确的实现?
这个question 不是重复的,它很相似,但它是关于两个独立的控制器(即使答案表明代码甚至不需要条件依赖注入),在我的情况下,运行时需要条件依赖基于客户端属性值。
【问题讨论】:
-
你不能在这里使用条件注入,因为依赖的类型将在运行时确定,并且可以随着每个
DoOrder调用而改变。所以你需要注入这两个实现。 -
不是依赖注入问题。看起来你需要Factory Design Pattern。看看
标签: c# dependency-injection .net-core