I am working on enterprise application using MVC, Nhibernate and IOC container.
I three tiers:
DAL – Nhibernate Data Repositories
public class CustomerRepository : Repository<int>,ICustomerRepository
{
public CustomerRepository(IUnitOfWork unitOfWork)
: base(unitOfWork)
{
}
}
BLL – Business Layer
public class CustomerManager
{
private readonly ICustomerRepository _repository;
public CustomerManager(ICustomerRepository repository)
{
_repository = repository;
}
public IList<Customer> GetAll()
{
return _repository.GetAll<Customer>();
}
}
Presentation – MVC controller
private readonly IUnitOfWork _unitOfWork;
private readonly ICustomerRepository _repository;
private readonly CustomerManager _manager;
public HomeController(IUnitOfWork unitOfWork, ICustomerRepository repository)
{
_unitOfWork = unitOfWork;
_repository = repository;
_manager = new CustomerManager(_repository);
}
I am using IOC container to register unit of work and CustomerRepository objects. The IOC container is working fine.
What is bugging me about this solution is that I have CustomerRepository reference in the controller. Is this architecture fine or there is a better way to implement this?
You shouldn’t need/have a
IUnitOfWorkorICustomerRepositoryin the controller, with the IoC container you should be able to register theCustomerManagerand then do this:The IoC container should understand the dependency chain and inject all the various dependencies as needed.
I.e. MVC will try and get a
HomeControllerfrom the IoC container, which in turn needs aCustomerManager… so the IoC container will try and get aCustomerManager, which in turn needs aICustomerRepository… so the IoC container will try… you get the point.I would also go the the extent of extracting an interface from
CustomerManager(ICustomerManagerprobably) to remove the coupling and make testing the Controller even easier.