From inside to outside, these are our MVC app layers:
- MS SQL / Tables / Views / Stored Procs
- Entity Framework 4.1 (ORM) with POCO generation
- Repository
- Service (retrieve) and Control Functions (Save)
- Routing -> Controller -> Razor View
- (client) JQuery Ajax with Knockout.js (MVVM)
Everything is fine until I need to create a single ViewModel for step 5 to feed both the Razor view as well as the JSON/Knockout ViewModel:
- Header that includes all Drop down list options and choices for the fields below
- Items – an array of whatever we send to the client that becomes the ViewModel
Since the Controller won’t have access to the Repository directly, does this mean I create a service for each and every view that allows editing content? I’ll need to get the POCO from the repository plus all options for each field type as needed.
It just seems redundant to create separate services for each view. For example, a viewModel to edit an address and a separate viewModel to edit a real estate property that also has an address. We could have a dozen forms that edit the same address POCO.
To make this question easier to answer, is allowing the Controller direct access to the repositories a leaky abstraction?
Well, so are your controllers going to have code that translates POCOs from Entity Framework into separate view model objects?
If so, then you should move that code to a separate class, and follow the single-responsibility principle. Whether that class is in the “service layer” or not is up to you. And whether you use AutoMapper or not is up to you. But these kind of data mappers should not be part of the controller logic; controllers should be as dumb as possible.
OK, now let’s ignore the data mapping problem, and pretend you could always use your POCOs directly as view models. Then you would still want a service layer, because it would translate between
in your dumb controller, and implement that in a specific manner by returning
Putting these together, your
UserControllerends up taking inIUserServiceandIUserDataMapperdependencies, and the code is super-dumb, as desired:You can now test the controller with stubs for both dependencies, or stub out
IUserDataMapperwhile you mockIUserService, or vice-versa. Your controller has very little logic, and has only one axis of change. The same can be said for the user data-mapper class and the user service class.I was reading an article this morning that you might find somewhat illuminating on these architectural matters. It is, somewhat condescendingly, titled “Software Development Fundamentals, Part 2: Layered Architecture.” You probably won’t be able to switch from a database application model to the persistent-ignorant model the article describes and suggests. But it might point you in the right direction.