Search code examples
c#dependency-injectionsimple-injector

How to inject list of base interfaces to class


I have a program where I have some services with custom interfaces but all of them inherit from IService. The services are registered with their custom interfaces as singletons in Simple Injector container but in one main class I want them all injected to constructor with IEnumerable<IService>. This is not working because IEnumerable<IService> is not registered. My question is how to configure container to allow retrieve those in constructor – I could manually resolve types but I should avoid this anti-pattern.

// sample service (one of many)    
public interface IHttpServerService : IService
...
_container.RegisterSingleton<IHttpServerService, HttpServerService>();
...
public Controller(IEnumerable<IService> services)
...

Solution

  • Just add:

    container.RegisterSingleton<IHttpServerService, HttpServerService>();
    
    container.Collection.Register<IService>(
        typeof(IHttpServerService),
        // more implementations here
    );