dimanche 5 juillet 2015

Single responsibility principle in MVC

I have a MVC project with following pattern

View <-> Controller <-> Service <-> Repository/Entities <-> Database

For example, if I have 2 tables (Customer and Order) in my Database, then I have 2 classes in my Repository layer (this class map 1:1 with my database table because I'm using EF Code First) :

public class Customer
{
     [Key]
     public int CustomerID { get; set; }
     public int Name { get; set; }
     //rest of columns here
}

public class Order
{
     [Key]
     public int OrderId { get; set; }
     //rest of columns here
}

Then I have services :

public class CustomerService : ICustomerService
{
     void AddNewCustomer(Customer obj);
     void GetCustomerOrders(Customer obj);
     //rest of methods here
}

public class OrderService : IOrderService
{
     void GetOrderById(int id);
     void GetCustomerOrders(Customer obj);
     //rest of methods here
}

you probably notice that I have GetCustomerOrders.

My question :

  1. Without breaking Single responsibility principle rule, where do I put GetCustomerOrders? In CustomerService, OrderService, or both?

  2. Did I break the Single responsibility principle rule by having more than one service in my controller? For example :

     public class TransactionController : Controller
     {
          //more than 1 service inside this class
          private ICustomerService _customerService;
          private IOrderService _orderService;
    
          public ProjectController()
          {
              this._customerService = new CustomerService();
              this._orderService = new OrderService();
          }
    
          public ProjectController(CustomerService customerService, OrderService orderService)
          {
              this._customerService = customerService;
              this._orderService = orderService;
          }
    
          public ActionResult Index()
          {
               Return View();
          }
    
          public ActionResult CreateCustomer()
          {
               //rest of code here
          }
    
          public ActionResult CreateOrder()
          {
               //rest of code here
          }
     }
    
    
  3. I have bunch of controller with bloated Action method, for example ProductController could have Index, Add, Edit, Delete, Priority, AddPriority, EditPriority, RemovePriority, etc. My question is should I split my ProductController into ProductController, ProductPriorityController because I see that the template project from Microsoft doesn't have more than one CRUD operation inside their Controller.

Any help will be appreciated and apologize for bad english.

Aucun commentaire:

Enregistrer un commentaire