.NET by Patrik

Registering Multiple Implementations in Dependency Injection

In .NET applications, it’s common to have multiple classes that share the same interface or base class. Instead of registering each class manually in the Dependency Injection (DI) container, you can register them all automatically by scanning the assembly.

Here’s a simple example:

var serviceTypes = typeof(IServiceBase)
    .Assembly
    .GetTypes()
    .Where(t =>
        typeof(IServiceBase).IsAssignableFrom(t) &&
        !t.IsAbstract &&
        !t.IsInterface);

foreach (var type in serviceTypes)
{
    services.AddSingleton(typeof(IServiceBase), type);
}

// If you also need a concrete type directly
services.AddSingleton<SpecialService>();

// Example: register a factory or manager
services.AddSingleton<IServiceFactory, ServiceFactory>();

This pattern ensures:

  • All implementations of IServiceBase are available through IEnumerable<IServiceBase>.
  • Specific concrete classes can still be injected directly when needed.
  • The system automatically picks up new implementations without changing the registration code.
dotnet
dependency-injection
csharp
design

Comments