Inject Multiple Service Implementations in ASP.NET Core

Most people are familiar using an IOC container to facilitate dependency injection in their applications.  But have you come across a situation where you wanted to inject multiple implementations of an interface?  I have!  Using your IOC container when this need arises leads to a nice clean implementation.  Lets take a look at how this is done using the ASP.NET Core IOC Container.

Imagine we have the following IValidator interface.  We plan on having several classes that will implement this interface in order to validate some user input.  Our goal is to make managing these implementations simple and adding new ones as convenient as possible.

We can now wire our validators up like we would with any other service.  Note lines 13-15 below.

With everything registered, we can now use the magic of dependency injection to provide us with an IEnumerable containing each of our validators.  This allows us to easily loop through each implementation.

The best part is going forward adding (or removing) a validator is as simple as altering which implementations of IValidator are registered during startup.

 

 

 

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s