9

I haven MVC app, with "M" including Service and Repository layers.

However, I am a little confused as to where and how to do a couple of things.

  1. One Service calling two repositories, or calling it's own repository and another service

e.g.

I have a ReferenceDataService, which handles all of the logic for CRUD with my reference tables.

Then in my "CustomerService" I need to 'R' my reference data to get e.g. Description instead of Id. So, do I call the ReferenceDataService or ReferenceDataRepository?

  1. At some layer I'd like to map from Entity to ViewModel.

Do I do this in my Service layer, or in the Controller?

e.g. Does my ServiceLayer do the mapping/logic from VM to Entity and back?

Thanks:)

BlueChippy
  • 5,935
  • 16
  • 81
  • 131

2 Answers2

27
  • Repositories talk to an underlying data source.
  • Service layer talks to repositories with domain models. It takes/passes domain models from/to the repository layer.
  • Controller talks to service layer. Controller takes/passes domain models from/to the service layer.
  • Controller calls mapping layer (if any) to map between the domain models and view models. If you don't have a mapping layer you could do the mapping in your controller although this could quickly become cumbersome in which case AutoMapper could serve as a very handy mapping layer.

Another more simpler scenario is when you don't need a service layer which is often the case in smaller applications. A service layer brings no benefit. So the controller talks directly to the repositories with the domain models.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • Thx :) I think I may be deleting my service layer...it serves very little purpose in my application and I included it just because "it fitted the pattern". Doh! – BlueChippy Jul 18 '12 at 11:49
6

ViewModel contains data, required for displaying model on view. If you'll use another view (e.g. mobile application, or desktop application, or even web service) you will require another data to be displayed on view. If you'll do mappings on service layer, then you will not be able to use it with another type of application. Thus controller is a place where you map domain data to display them on view (whatever type of view you have).

Sergey Berezovskiy
  • 232,247
  • 41
  • 429
  • 459
  • I think another layer like an Interactor/UseCase could solve this issue, but I have mapped in the controller before. I'll add to your answer in saying that it's best to abstract the mapping functions to a separate file/utility to avoid bloat. I've seen many controllers/components stuffed with mapping logic. – GHOST-34 Mar 26 '21 at 19:35