Should a service layer return view models for an MVC application?

erg39 picture erg39 · Jun 9, 2010 · Viewed 20.7k times · Source

Say you have an ASP.NET MVC project and are using a service layer, such as in this contact manager tutorial on the asp.net site: http://www.asp.net/mvc/tutorials/iteration-4-make-the-application-loosely-coupled-cs

If you have viewmodels for your views, is the service layer the appropriate place to provide each viewmodel? For instance, in the service layer code sample there is a method

    public IEnumerable<Contact> ListContacts()
    {
        return _repository.ListContacts();
    }

If instead you wanted a IEnumerable, should it go in the service layer, or is there somewhere else that is the "correct" place?

Perhaps more appropriately, if you have a separate viewmodel for each view associated with ContactController, should ContactManagerService have a separate method to return each viewmodel? If the service layer is not the proper place, where should viewmodel objects be initialized for use by the controller?

Answer

captaintom picture captaintom · Jun 9, 2010

Generally, no.

View models are intended to provide information to and from views and should be specific to the application, as opposed to the general domain. Controllers should orchestrate interaction with repositories, services (I am making some assumptions of the definition of service here), etc and handle building and validating view models, and also contain the logic of determining views to render.

By leaking view models into a "service" layer, you are blurring your layers and now have possible application and presentation specific mixed in with what should focused with domain-level responsibilities.