jeudi 2 juillet 2015

MVC design pattern, service layer purpose?

Let's say I have a following repo pattern :

interface IGenericRepo<T> where T : class
{
     IEnumerable<T> GetAll();
     T GetById(object id);
     void Insert(T obj);
     void Update(T obj);
     void Delete(T obj);
     void Save();
}

interface ICustRepo : IGenericRepo<Cust>
{
     IEnumerable<Cust> GetBadCust();
     IEnumerable<Cust> GetGoodCust();
}

public class CustRepo : ICustRepo<Cust>
{
     //implement method here
}

then in my controller :

public class CustController
{
     private ICustRepo _custRepo;

     public CustController(ICustRepo custRepo)
     {
         _custRepo = custRepo;
     }

     public ActionResult Index()
     {
         var model = _custRepo.GetAll();
         return View(model);
     }

     public ActionResult BadCust()
     {
         var model = _custRepo.GetBadCust();
         return View(model); 
     }
}

Basically my pattern is something like

View <-> Controller -> Repo -> EF -> SQL Server

but I saw a lot of people doing this

View <-> Controller -> Service -> Repo -> EF -> SQL Server

So my question is :

  1. Why and when do I need service layer? Isn't that just add another unnecessary layer because every non-generic method is already implemented in ICustRepo?

  2. Should the service layer return DTO or my ViewModel?

  3. Should the service layer map 1:1 with my repo?

I've look around for few days but I haven't satisfied with the answers.

Any help will be appreciated and apologize for bad english.

Thank you.

Aucun commentaire:

Enregistrer un commentaire