Search code examples
asp.netasp.net-web-apidependency-injectionautofacunity-container

AutoFac / Unity Container - Dependency Injection with multiple implementations


I am going to work with Dependency Injection for a ASP.NET Web API project.

I understand how constructor Dependency Injection works, but i can't resolve how to make the injector choose between two implementations of the same interface. Lets say for an example that we have an interface like this:

public interface ISender
{
    void Send();
    void AddReceipment(User user);
}

Then lets say i have 2 implementations of this SmsSender and MailSender using the same ISender interface.

Now i have two API controllers lets call them "MailController" and "SmsController".

Now i want the dependency injector to inject ISender into the MailController with the implementation of the class MailSender and in the SmsController i want to inject ISender too, but with the implementation of the class SmsSender.

Is that possible using AutoFac or Unity container?

If it is, then how would i aproach that?


Solution

  • According to the Autofac docs, you have 4 options to achieve this:

    1. Redesign your interfaces
    2. Change the registrations
    3. Use keyed services
    4. Use metadata