Reputation: 71
I am using Autofac in my project. I want to use a simple interface to resolve them. Not generic repository.
I was using Castle in my old projects. It has a class which have static methods. I used it in my constructor method like this;
IService.ProductService.GetMyProducts();
In Autofac i couldnt find anything like above. Please help me. I dont wanna use a lot of Interfaces in my constructor.
private IGeneralRepository generalRep;
private IDenemeRepository denemeRep;
private IGokberkRepository GokberkRep;
public HomeController(IDenemeRepository dr,IGokberkRepository gr, IGeneralRepository ger)
{
generalRep = ger;
denemeRep = dr;
GokberkRep = gr;
}
Upvotes: 1
Views: 1381
Reputation: 8498
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();
}
Upvotes: 1