Asp.net-mvc – Creating a Service Layer for the MVC application

asp.net-mvcasp.net-mvc-3asp.net-mvc-4

From what I understand, MVC separates the class definitions (model) from the presentation (view) via the "glue" that is the controller. The controller should have a single responsibility and therefore be testable. ViewModels are used to bring together data from multiple entities and to "massage" the data from the controller for the view.

It seems like business logic doesn't really have a place… so I'm thinking another layer for services would be suitable. I'm just not sure where to place this layer, or how to build the services – should it be a class called "services" that contains a bunch of functions? I'm a bit new to MVC, so any reading material, samples, or general newcomer kind of tips would be awesome.

Best Answer

I usually use a Service Layer when developing ASP.NET MVC application. It is similar to the Service Layer Pattern that Martin Fowler discusses in Patterns of Enterprise Application Architecture. It encapsulates your business logic and make the controllers pretty thin. Basically the controllers use the service layer to get the domain models that are then transformed into view models. I also use the Unit of Work Design Pattern to handle transactions and the Repository Design Pattern to encapsulate the data access layer for easier unit testing and being able to easily swap out ORM's. This figure shows the typical layers that I use in an MVC application.

MVC Architecture

The service layer is labeled as the "Application or Domain Layer" in this diagram because I find people get confused when you use the term "Service Layer". They tend to think that this is a web service. It is actually an assembly which can be used by your favorite web service technology, such as ASP.NET Web API or WCF, as well as a controller.

As for naming conventions I usually use something that describes the domain followed by service. For example, If I have a service layer that handles user membership then I would have a class called MembershipService that has all of the methods needed by controllers and and web services to query and manipulate the membership domain. Note you may have several domains in the same application so you can have multiple service layers. My point being here that you do not have to have one monolithic service that takes care of the whole application.