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.