public void ConfigureServices(IServiceCollection services)
{
services.AddTransient<AddOperationRepository>();
services.AddTransient<SubtractOperationRepository>();
services.AddTransient<MultiplyOperationRepository>();
services.AddTransient<DivideOperationRepository>();
services.AddTransient<Func<MathOperationType, IMathOperationRepository>>(serviceProvider => key =>
{
switch (key)
{
case MathOperationType.Add:
return serviceProvider.GetService<AddOperationRepository>();
case MathOperationType.Subtract:
return serviceProvider.GetService<SubtractOperationRepository>();
case MathOperationType.Multiply:
return serviceProvider.GetService<MultiplyOperationRepository>();
case MathOperationType.Divide:
return serviceProvider.GetService<DivideOperationRepository>();
default:
throw new KeyNotFoundException();
}
});
. . .
}
...
public class ValuesController : ControllerBase
{
private Func<MathOperationType, IMathOperationRepository> _mathRepositoryDelegate;
public ValuesController(Func<MathOperationType, IMathOperationRepository> mathRepositoryDelegate)
{
_mathRepositoryDelegate = mathRepositoryDelegate;
}
[HttpPost]
public ActionResult<OperationResult> Post([FromBody] OperationRequest opRequest)
{
IMathOperationRepository mathRepository = _mathRepositoryDelegate(opRequest.OperationType);
OperationResult opResult = mathRepository.PerformOperation(opRequest);
return new ObjectResult(opResult);
}
}
Source:
https://www.c-sharpcorner.com/article/dependency-injection-with-multiple-implementations-of-the-same-interface/