I Have an MVC Project roughly organized like this:
- Project 1: MVC app (ViewModels, Controller, Actions, UI-stuff)
- Project 2: Domain Model (Domain Classes, behavior, Data Access (Persitance layer, Repositories)
My question is where to do mapping and data access (how to organize the code).
By definition (as I understand it) the controller should map the request to the right view and be as skinny as possible.
I use Automapper on the basic mapping, and I do it in the controller, but for more complex mapping I find it easier to do the mapping myself.
I have mainly two places to put the code for this:
- In the controller:
This can easily get quite messy, specially if I need to get information from several repositories, create select lists and so on.
- In the ViewModel:
This feels better, but I don’t like instansiating Repositories and UnitOfWork in the model. Don’t know if that belong there.
Right now I’m doing something in between:
I let the ViewModel take the needed repositories as contructor
parameters, and I do the mapping there. I instansiate the
Repositories/UnitOfWork in the controller and pass it in. The good
thing is that I can use an Interface for the repositories so the
ViewModel doesn’t need to care about implementation.
However, in examples on the web I always see all this code in the controller so that makes me wonder – what is the right way to do it?
In order to do it in the ViewModel, that would mean your viewmodel has to understand your other object. That’s not good. The ViewModel should be as dumb about external dependencies as possible.
You should be doing the mapping in the controller.