ASP.NET Core: Inject all instances of a service interface
When it comes to Dependency Injection (DI), the functionality provided by ASP.net core is simple, but powerful.
I was stunned by how easy it is to resolve multiple registered implementations for a registered service interface in ASP.net core.
To create some context, let’s say you’re creating invoices for your project and you need to support multiple currencies (EUR, USD, GBP). One way to handle this, would be to create a specific service per currency, provide an interface on which they need to abide to. So that you can call upon them in a uniform way.
The interface requires the implementor to return a text version of the invoice value for a currency.
Now that we have our multiple implementations ready, we’ll need a way to register them in our DI registry.
This helper function scans the provided assemblies and registers all implementations for a specific type as a transient service.
Since the services contain pure functions, they could also be registered as a singleton without any negative effects. But I’ll discuss lifetime and registration in a different article.
We’re almost set, all we now need to do is the actual registration, which is typically done in the Startup file of an ASP.net core project.
Looking at line 15, we’ll see the registration of the multiple service implementations in action.
To consume the services, this is what excited me most, you only need to depend on an IEnumerable<IDependency> in your consuming constructor and the ASP.net core DI library does all the work!
Line 7 portrays the magic of DI.
If you’d run the code from the multiregister repository, you should see the output in your browser on http://localhost:7000/api/invoices?hoursPerformed=8