Conditional dependency resolver on run-time (.net Core)

前端 未结 3 1392
囚心锁ツ
囚心锁ツ 2021-01-06 11:26

I have two classes PaymentGatewayFoo, PaymentGatewayBoo that both implements a common interface of IPaymentGateway:

in         


        
3条回答
  •  遥遥无期
    2021-01-06 12:15

    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();
    }
    

提交回复
热议问题