ASP.NET Core: Inject all instances of a service interface<T>

Maarten Merken
Agilix
Published in
2 min readDec 29, 2018

Earlier this year, I wrote about injecting all instances of a service interface in a ASP.NET Core controller using the out of box DI system. Recently I’ve received the question on how to tackle this using a typed IDependency, an IDependency<T>.

To demonstrate this, I’ll rewrite the code sample from the article mentioned above. We’ll inject all invoicing services that can handle the Euro currency. For this, we’ll need to rethink our approach, instead of having multiple invoicing services that derive from a specific base interface, we’ll implement one CurrencyInvoicingService<T> where the T is a Currency type. There are three currencies that derive this type, Euro, Dollar and Pound Sterling (GBP).

At the base of the invoicing service, there’s one interface that replaces the IInvoicingService, I called it ICurrencyInvoicingService to avoid naming collisions.

This interface accepts a generic type (T) which is the base class Currency.

The CurrencyInvoicingService class will create an instance of the currency type (EUR, USD, GBP) and have one implementation for the CreateInvoice method, no more fragmentation.

We could still have an ICurrencyInvoicingService for a specific currency, like a low tax Euro invoicing service (6% VAT).

To have this working, we’ll register the two Euro services in the Startup file.

To have these ICurrencyInvoicingService<Euro> (IDependency<T>) services injected, the InvoicesController needs to inject a list of Euro typed services.

The result should be reflected in the browser after you spin up the application.

Please check out the updated GitHub repo for the full implementation!

Thanks for reading, happy holidays!

--

--