Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I register and resolve multiple implementations for a service?

Can I register multiple implementations of a given service interface?

services.AddTransient<ISerivce, Service1>();
services.AddTransient<ISerivce, Service2>();
services.AddTransient<ISerivce, Service3>();

And, then, how do I inject or resolve all of the registered implementations in an array or list?

var services = myTypedFactory.ResolveAll();
myCustomFactory.Release(services);
like image 553
user2368632 Avatar asked Oct 28 '25 20:10

user2368632


1 Answers

Given multiple registrations in Startup.cs

public void ConfigureServices(IServiceCollection services)
{
    services.AddTransient<IService, ServiceA>();
    services.AddTransient<IService, ServiceB>();
    services.AddTransient<IService, ServiceC>();
}

You should be able to depend on an IEnumerable<TService> in the depending service.

public Foo(IEnumerable<IService> services)
{
    this.services = services;
}

This does not appear to be documented yet, although, strangely, the opposite behavior is documented as the TryAdd* methods.

like image 179
Anthony Mastrean Avatar answered Oct 31 '25 12:10

Anthony Mastrean