I have two classes PaymentGatewayFoo, PaymentGatewayBoo that both implements a common interface of IPaymentGateway:
in
After trying to implement the great answers here, it looks like that the native DI .net core container does not support injecting of numerables (like IPaymentGateway[] as @armand suggested) so I ended up with a delegate resolver based on switch case (not on reflection in order to save performance):
startup.cs
services.AddTransient(serviceProvider => key =>
{
switch (key)
{
case E_PaymentGatewayType.Foo:
return serviceProvider.GetService();
case E_PaymentGatewayType.Boo:
return serviceProvider.GetService();
case E_PaymentGatewayType.Undefined:
default:
throw new NotSupportedException($"PaymentGatewayRepositoryResolver, key: {key}");
}
});
The delegate:
public delegate IPaymentGateway PaymentGatewayResolver(E_PaymentGatewayType paymentGatewayType);
The client order service:
private readonly PaymentGatewayResolver _paymentGatewayResolver;
public OrderService(PaymentGatewayResolver paymentGatewayResolver)
{
this._paymentGatewayResolver = paymentGatewayResolver;
}
public DoOrder(E_PaymentGatewayType paymentGatewayType)
{
IPaymentGateway paymentGateway = this._paymentGatewayResolver(paymentGatewayType);
paymentGateway.Pay();
}