1

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.

1 Answer 1

1

Make the following registrations instead:

services.AddScoped<DesignerService>();
services.AddScoped<CheckerService>();

Notice that both DesignerService and CheckerService are no longer registered by their interface, but rather their concrete type. This is needed, because you request them by their concrete type.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.