I can think of two ways to reduce number of injected services in your constructor.
First, in Autofac you can have a single parameter of type IComponentContext
, and when your service is resolved from a container instance, IComponentContext
dependency is automatically resolved to the instance of the container. Then you can resolve the rest of your dependencies from it:
// constructor of your component
public MyComponent(IComponentContext components)
{
_serviceA = components.Resolve<IServiceA>();
_serviceB = components.Resolve<IServiceB>();
}
BTW, in Castle Windsor you had to explicitly register the instance of the container in order to make the above method work.
Second way is creating one "composite" service which contains all (or the most common) services the application needs. Then inject that service and get all the others from it:
// composite service - implement this interface as shown below
public interface ICommonServices
{
IServiceA ServiceA { get; }
IServiceB ServiceB { get; }
}
The composite service implementation:
// a class that implements ICommonServices interface
public class CommonServices : ICommonServices
{
public CommonServices(IServiceA serviceA, IServiceB serviceB)
{
this.ServiceA = serviceA;
this.ServiceB = serviceB;
}
public IServiceA ServiceA { get; private set; }
public IServiceB ServiceB { get; private set; }
}
Note that you must register the composite service and the inner services in the container.
Now you can have only one parameter in your constructor:
public MyComponent(ICommonServices services)
{
_services = services;
}
Using the inner services:
public void SomeMethod()
{
_services.ServiceA.DoSomething();
}