0

I am creating a ASP.NET Core Rest API application.

On Controller, depending upon the value of parameter we need to create request processor {job of the processor is to further process the request and perform business logic}.

Now with .net core DI how can we construct object when we have some condition to execute on run-time data before system identify what type of object we need to create/construct.

I can think of ServiceLocator, but it's anti-pattern. What should be proper approach to solve it.

Example Code:

Here we have a controller to calculate Fees, and this calculation depends on few values of the request object (Payment)

Now the calculation logic is different for values of Payment, but both parameter and return values of both services (inbound/outbound) are same

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

Via .net core DI, we can create both the service instances, but only one of them will be needed for a particulate request.

Posto
  • 7,362
  • 7
  • 44
  • 61

1 Answers1

1

You can register multiple classes which implements your interface and inject them as IEnumerable in constructor.

public PaymentController(IEnumerable<IPaymentService> services) {}

After that you can get specific instance using Linq for example. Add custom property to your interface, which will define your type.

Cleaner approach would be writing your own service resolver - factory.

Examples already here How to register multiple implementations of the same interface in Asp.Net Core?

Note, writing conditional over service.calculate, i would rather remove it and just call the method, keeping OOP polymorphism handle your work but that's depends on your injected instance.

apincik
  • 341
  • 4
  • 14