Sobes.tech
Junior — Middle

Is it possible to register more than one implementation of the same interface within a single container?

sobes.tech AI

Answer from AI

Yes, in dependency injection containers (DI containers) in C# it is possible to register multiple implementations of the same interface. This is usually done when different behavior options are needed, which can be selected based on the context.

For example, in Microsoft.Extensions.DependencyInjection, you can register multiple implementations like this:

services.AddTransient<IService, ServiceImplementationA>();
services.AddTransient<IService, ServiceImplementationB>();

In this case, if you request IEnumerable<IService>, the container will return all registered implementations. If you request just IService, the last registered implementation will be returned (depending on the specific DI container).

To select a specific implementation, named registrations or factories are often used, or IEnumerable<IService> is injected and the desired implementation is chosen programmatically.