4

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);
2
  • 2
    So you want to create a factory around the resolving of the services? The asp.net core DI is able to allow resolve using services.GetService<IEnumerable<IService>> out of the box Commented Oct 26, 2017 at 19:31
  • @MartinUllrich is this documented anywhere? it's been 3 years and I still can't find any relevant docs! Commented Jun 24, 2020 at 16:36

1 Answer 1

6

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.

Sign up to request clarification or add additional context in comments.

5 Comments

Note: IList<T> or IService[] does not work. IEnumerable<T> is the only way to go.
@StephanSchinkel thanks! Do you know if there is any reason why?
@BendEg: i assume -> Performance. But This knowledge is nearly 3,5 years old. Take everything with a grain of Salt. .net has undergone some serious refactorings since then.
@StephanSchinkel it is still only working with IEnumerable<> i will research why, thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.