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?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x