Shankar
Shankar

Reputation: 337

Interface between Controller and Service Layer

I am a newbie to .Net MVC and my question today is regarding the MVC pattern.

In our application we have a Service Layer which talks with the DB.

The Controller is Currently talking with the Service layer to get the values from the DB.

Our new Manager requires this service layer interaction from the Models and not from the Controller.

He does say that this architecture is to achieve a thin Controller. We are now starting to port the service layer interaction from controller to models.

And here comes my question. Apart from having a thin Controller, is there any other benefits from enforcing this pattern.

I would like to know the advantages and disadvantages of both pattern.

Some links would also be helpful

Upvotes: 1

Views: 3594

Answers (2)

Md Nazmoon Noor
Md Nazmoon Noor

Reputation: 3307

There are 3 types of Models - View Model, Domain Model and Data Model. Check here.

If you are talking about View Models then its a bad idea. There are ways to achieve a thin controller, but ViewModel never should interect with services. If its possible a Controller Action should only invoke a service and throw the result to View. Like this:

[HttpGet]
public ActionResult GetAnimals(int id) 
{
    var viewModel = new AnimalsService(id).GetViewModel();
    return View(viewModel);
}

But in reality many times you can't do that for some obvious reasons. There are few things you can do though. Like don't validate models in controller, you can do that in service layer. Don't hesitate to create more services for different jobs, like pagination, context related logic or some third party api invocation. Create helper or utility classes for repititive codes. Also I think its ok to write fat services.

Upvotes: 2

Sam Leach
Sam Leach

Reputation: 12956

Why you shouldn't call services from your ViewModels:

ViewModels are supposed to be classes that contain some data that is interchanged between the View and the Controller. They should not perform any action or retrieve further data. They are dumb models, they don't do anything expect transport data.

What is a View Model

If you are having trouble understanding what a View Model is and what it isn't, think of it like a subset of your model. It only contains data that you need to display on a given view at a given time.

Upvotes: 4

Related Questions