How do I inject a list of all of the registered implementations for a given service interface?
public class Thing
{
public Thing(IList<IService> services) { }
}
public class ServiceA : IService { }
public class ServiceB : IService { }
public class ServiceB : IService { }
Given registrations like this:
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services
.AddTransient<IService, ServiceA>()
.AddTransient<IService, ServiceB>()
.AddTransient<IService, ServiceC>();
}
}
ASP.NET Core injects objects of dependency classes through constructor or method by using built-in IoC container. The built-in container is represented by IServiceProvider implementation that supports constructor injection by default.
Using the delegate func Introduce three implementation classes as below- three different classes where we have implemented the same interface. ASP.NET Core has built-in support for dependency injection. However, multiple implementations of an interface in ASP.NET Core is tricky.
As of ASP.NET Core 2.0, if you inject your dependencies as IEnumerable<IService>
instead of IList<IService>
, you can forgo registering the list itself, leaving you with just the individual services registration.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With