mpakbaz
mpakbaz

Reputation: 496

How do you resolve a specific keyed service in ASP.NET Core when using Autofac?

I created in simple ASP.NET Core web API, Let's say I have an interface as below:

public interface ITestService
{
    string GetDate();
}

I am using Autofac to handle DI, for the above interface I have two registered types (TestService and TestComponent implementing ITestService) :

builder.RegisterType<TestService>().As<ITestService>().Keyed<ITestService>("service");
builder.RegisterType<TestComponent>().As<ITestService>().Keyed<ITestService>("component");

I know for a fact that I can register my type to use either of these bindings, and I know there is a way to get the proper type as discussed here:

var services = serviceProvider.GetServices<ITestService>();
var testComponent= services.First(o => o.GetType() == typeof(TestComponent));

Since I am using Autofac and registered my types using Keyed Services, how do I resolve the proper ITestService using IServiceProvider and the key I provided in my bindings ("service" or "component")?

Upvotes: 5

Views: 2492

Answers (1)

Alex Riabov
Alex Riabov

Reputation: 9175

As per documentation there are two more clean ways to resolve keyed services. You can resolve using an index:

public class TestServiceConsumer
{
    private ITestService testService;    

    public TestServiceConsumer(IIndex<string, ITestService> testServices)
    {
        testService = testServices["service"];
    }
}

It also can be done with Attribute (it seems more suitable to your case):

public class TestServiceConsumer
{
    private ITestService testService;    

    public TestServiceConsumer([KeyFilter("service")] ITestService testService)
    {
        this.testService = testService;
    }
}

Upvotes: 2

Related Questions