I have two services that implement the same interface. Following the answer How to register multiple implementations of the same interface in Asp.Net Core? I have simplified code like
Interface:
public interface ICheckService
{
Method1();
Task Method2();
}
CheckerService:
public class CheckerService : ICheckService
{
private readonly DapperContext _context;
private readonly ILogger<CheckerService> _logger;
public CheckerService(DapperContext context,ILogger<CheckerService> logger)
{
_logger = logger;
_context = context;
}
}
DesignerService:
public class DesignerService : ICheckService
{
private readonly DapperContext _context;
private readonly ILogger<DesignerService> _logger;
public DesignerService(DapperContext context,ILogger<DesignerService> logger)
{
_logger = logger;
_context = context;
}
}
In my Startup.cs file:
public delegate ICheckService ServiceResolver(string key);
...
services.AddScoped<ICheckService, DesignerService>();
services.AddScoped<ICheckService, CheckerService>();
services.AddScope<ServiceResolver>(serviceProvider => key =>
{
switch (key)
{
case "DesignerService":
return serviceProvider.GetService<DesignerService>();
case "CheckerService":
return serviceProvider.GetService<CheckerService>();
default:
throw new KeyNotFoundException();
}
});
And in the Controller:
private readonly ICheckService _checklistService;
public DesignerController(ServiceResolver serviceAccessor)
{
_checklistService = serviceAccessor("DesignerService");
}
But after launching the code, I find that the returned service is null. But if I remove the switch code and change controller constructor to
public DesignerController(ICheckService checkService)
{
_checklistService = checkService;
}
the everything is fine.
Could someone tell me where I did wrong? Thank you.