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

前端 未结 3 1388
囚心锁ツ
囚心锁ツ 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:05

    This is how I approach this type of problem where I have cases that needs different implementations.

    public abstract class PaymentGateway : IPaymentGateway 
    {
        public long Identifier {get;}
        ...
    }
    
    public class PaymentGatewayFoo : PaymentGateway
    {
        public long Identifier => 1;
        ...
    }
    
    public class PaymentGatewayBoo : PaymentGateway
    {
        public long Identifier => 2;
        ...
    }
    
    public class PaymentGatewayProvider
    {
        private IPaymentGateway[] gateways;
        public PaymentGatewayProvider(IPaymentGateway[] gateways)
        {
             this.gateways = gateways;
        }
    
        public IPaymentGateway GetGateForClient(bool f) //This can be anything that you can use to identify which payment gateway you need
        {
             //As an example I would usually pass in a client or something that I can then use to identify which payment provider is mapped to a certain client, this way you can have hundreds of payment providers, but in your case you just had a boolean, so I used that
             if(f)
                  return gateways.First(f=> f.Identifier == 1);
             return gateways.First(f=> f.Identifier != 1);
        }
    }
    
    
    public class OrderService
    {
        private readonly PaymentGatewayProvider _provider;
    
        public void DoOrder(bool isFoo)
        {
            var service = _provider.GetGateForClient(isFoo);
            this._service.Pay();
        }
    }
    

    The way you identify payment providers can be anything, I just used longs as an example here, but you can map it to an enum and rather use that to do identification, then you pass the enum to the GetGateForClient method to get the correct payment gateway

    This might not compile out of the box, but should give you a general idea of how to solve the problem.

提交回复
热议问题