Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I inject all implementations for a given service?

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>();
      }
  }
like image 411
Anthony Johnston Avatar asked May 01 '16 14:05

Anthony Johnston


People also ask

How can we inject the service dependency into the controller?

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.

CAN interface have multiple implementations C#?

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.


1 Answers

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.

like image 183
Gabriel Rainha Avatar answered Oct 02 '22 02:10

Gabriel Rainha