C# – MVC 3 – Controllers and ViewModels – Which should contain most of the business logic

asp.net-mvc-3ccontrollersmodel-view-controllerviewmodel

Currently in my application and using the unit of work pattern and generic repository, all my controllers contain all of the business logic. I'm in the process of putting everything over to use ViewModels instead of the straight Model.

While this is a good idea, now comes a question that can significantly separate my business logic in the controllers. For controllers and ViewModels, which should contain most of the business logic?

I've tried a few ways to get my ViewModels to practically contain all the business logic. However, I do have to have an argument in my ViewModel's constructor that takes a Unit of Work. Is this a good idea?

My code smell tells me it is. However, I am just a little worried how this will be in consistency with controllers that perform actions that do not need ViewModels. Simply put, actions that do not require to pass a Model/ViewModel to a View; this case happens on actions that do redirects to other actions. Which means, my business logic can either stay in that action or I could separate that business logic into a function.

What is the best practice here?

Best Answer

I can't say that my approach is a best practice, but I prefer to put any business logic in a separate "service" layer.

I tend to use the ViewModel to only store the properties required for a specific view. If there are any methods on the ViewModel, they are likely just to retrieve collections related to that view.

I keep my controllers lightweight by trying to limit them to validation and redirection/displaying views as much as possible.

So if I have any complex logic, I'll have a controller action call out to a separate service just to handle that logic. This way the logic is isolated which makes it easier to test since there's no longer a need to create a controller or ViewModel to test it. It's also easier to reuse a service than to pick apart a ViewModel.

Hopefully this helps. Good luck.