Mvc – Use a service layer with MVC

mvcservices

If a controller gets too fat and model instantiation starts to add up, a service layer could be used.

  • If I just wrap the logic inside a service class, I will get a bunch of Services with one/two methods. This feels like a code smell. Any best practices regarding this?

  • Can a service instantiate models?

  • If a service instantiates models, the services can't be unit tested. They can only be covered by integration tests?

Best Answer

In 'SOLID' the 'I' stands for Interface Segregation. The whole idea of this principle is to split large interfaces into smaller ones, more modular. In MVC service would normally have an interface that controller would rely upon. You don't want your controllers to know about concrete implementation of that service. Therefore, a bunch of services with one or two methods is a good thing to have.

Services normally return DTOs in large applications or domain models directly in smaller applications. DTOs normally means more work, but better separation of concerns. The typical flow is:

  • Controller calls service
  • Service returns an object (be it a DTO, domain model or something else)
  • Controller maps DTO/domain model to a view model

Mapping can be done manually, but most developers prefer to use auto mapping framework such as Automapper because we don't like writing plumbing code and we can be quite lazy :-)

http://en.wikipedia.org/wiki/Interface_segregation_principle

https://github.com/AutoMapper/AutoMapper

One of many discussions on stackoverflow regarding use of DTOs and domain models: https://stackoverflow.com/questions/2680071/dto-or-domain-model-object-in-the-view-layer

Related Topic