jeudi 30 avril 2015

Is calling service from controller a violation of MVC?

I have seen many code references online they use services directly in the Controller.

public class PersonController : Controller
{
   public ActionResult Index(int personId)
   {
       Person personDataModel = null;
       using(var service = new Personservice())
       {
          personDataModel = service.GetPerson(personId);
       }

       var personVM = MapPersonDataModelToViewModel(personDataModel);

       return View("Index",personVM);
   }
}

As per MSDN, Controllers are the components that handle user interaction, work with the model, and ultimately select a view to render that displays UI.

Where is the mention of Service? I know people talking about Service layer pattern or SOA architecture. But still is this a violation. A violation for convenience?

For some reason, if I want to do away with services. Then I'll end up changing the controller. And have to build my model. Instead I'm suppose to change only the Model.

I feel Model should have the intelligence to serve the request from Controller either by calling external service or by itself.

public class PersonController : Controller
{
   public ActionResult Index(int personId)
   {
       var personVM = PersonModel.GetPerson(personId);

       return View("Index",personVM);
   }
}

public class PersonModel
{
   public PersonVM GetPerson(int personId)
   {
      Person personDataModel = null;
       //Can either do this
       using(var service = new Personservice())
       {
          personDataModel = service.GetPerson(personId);
       }

       //Or can do this
       personDataModel = GetPersonDataModel(personId);

      var personVM = MapPersonDataModelToViewModel(personDataModel);

      return personVM;
   }
}

I know PersonModel needs re-factoring but that's not the point.

Am I missing something. Please share your valuable thoughts.

Aucun commentaire:

Enregistrer un commentaire