Nested Interface (empty) Dependency Registration

Viewed 22

I have a parent interface that is empty, and its only purpose is to implement 2 other child interfaces. This way I can reduce the number of constructor parameters to an acceptable count. The problem is I dont know how to register this dependency in the container since there is no implementation of the parent Interface. Entries are present for the child services, but the dependent services are unable to find the required service dependencies for both children at this point.

services.AddScoped<IServiceChild1, IServiceChild1>();
services.AddScoped<IServiceChild2, IServiceChild2>();
// how to register IServiceParent

public interface IServiceParent: IServiceChild1, IServiceChild2
{
} 
1 Answers

Make it a class instead:

public class ServiceParentServices
{
    public IServiceChild1 Service1 { get; }
    public IServiceChild2 Service2 { get; }
    public class ServiceParentServices(IServiceChild1 service1, IServiceChild2 service2)
    {
        Service1 = service1;
        Service2 = service2;
    }
}

Register this class to the ServiceCollection, and when you want to consume it, just inject ServiceParentServices into the constructor

public class ServiceParent
{
    private ServiceParentServices _services;
    public ServiceParent(ServiceParentServices services)
    {
        _services = services;
    }
}

As an alternative you could also inject IServiceProvider, but this more like the ServiceLocator anti pattern.

Related