I am using ASP.NET MVC 3.
I’m still confused as to how much can happen in a repository layer. I’ve always been under the assumption that it must just do what is needed and nothing more.
I have always worked with a service layer that in turn calls my repository layer. I always had a corresponding service layer for a repository layer, and a corresponding service layer method for a repository method, even if it just to get a list of items. So I would have the following service layer:
public class UnitService : IUnitService
{
private readonly IUnitRepository unitRepository;
public UnitService(IUnitRepository unitRepository)
{
this.unitRepository = unitRepository;
}
public IEnumerable<Unit> GetAll()
{
return unitRepository.GetAll();
}
}
This is what my repository layer could look like:
public class UnitRepository : IUnitRepository
{
// Partial code
public IEnumerable<Unit> GetAll()
{
return DbContext.Units
.Include("Department")
.OrderBy(x => x.Name);
}
}
I am trying to reduce my service layer classes if it isn’t really needed. So would it be ok just to call the repository from my controller instead of the service layer? Does it really matter if I do it my way or not? I mean it still brings back all my data.
Where would I do caching and logging? Service layer or in the repository? Let say that the GetAll methods brings back alot of records that needs to be cached. Would I cache this in the repository or would I need a service layer for this?
The same goes for logging. Where would I log stuff like:
Log.Info("Adding category: {0}, {1}", entity.Id, entity.Name);
// adding code
Log.Info("Category added: {0}, {1}", entity.Id, entity.Name);
If all that your service layer methods do is to delegate the call to the underlying repository method then yes, it is perfectly fine to remove this service layer as it has no added value and directly use the repository from your controller.
Caching should be done at the data layer. Depending on how you are doing your data access, ORMs such as NHibernate already include second level cache, so all you have to do is to activate it.
As far as logging is concerned, you could do that in absolutely every layer of your application that might require logging something.