ASP.NET MVC – Repository Pattern with Service Layer

architectural-patternsArchitectureasp.net-mvcdesign-patterns

I have an MVC site which uses the repository pattern. I don't feel like I'm using the MVC style enough, so I'm getting ready to re-architect some of it. But I'm also wanting to do it so if the front-end ever changes, it will be easier to swap out.

Here's what I have currently

Models – some of my models contain my entities/classes directly. (Login model contains Customer class, which is a direct correlation to the Customer table/repository class)
Views – some of my views contain repo queries – ie

_customerRepo.Query().FirstOrDefault(c => c.Login == User.Identity.Name);

Controllers – Not as big of a deal here, controllers calling some repo queries, and some of them also use some services to call the repos – ie

_customerService.GetAllCustomers()

which calls

_customerRepo.Query().All();

Here are my thoughts:

1) Models should contain ONLY the data needed to be presented on the view. Even if all properties of the Customer table/object are presented on the view, they should be re-written to their own model/class so the view knows nothing about the database architecture or backend objects

2) Views should only be accessing model objects

3) (And this is where I'm struggling on which path to take)

a) Controllers (or somewhere on the MVC side, should be code that converts the object data returned from the repo/services and converts them to the models. I'm assuming I could just place this code in a model constructor. But I've noticed that DI expects a default empty constructor in case there are validation errors

b) Controllers call repo interfaces on well-named methods to retrieve data (ie _customerRepo.GetAllCustomers()

c) Controllers ONLY access a service layer. The service layer then is the only thing that interacts with the repo layer.

Am I trying to extract the model, controller, service, repo layers too much? Is the serivces layer too much overhead since it can all be done by the repos?

What's the recommended approach to converting the objects/business entities to the models?

Best Answer

Yes, the service layer is an overhead if you don't have any business logic there. Layered architecture looks like an overhead when a layer (in your case service) is not doing much. But a layered architecture provides your loose coupling which is generally good for adapting requirements in future.

If you can guarantee that you will never need to do anything in service layer except data copy from repo to model then you can remove the service layer in your design. However if your application is basic then you don't have to worry about adding another layer for performance or other reason.

Personally I will keep the service layer and (depends on the technology) will implement a generic DAO/Repository layer.

Related Topic