MVC中的单一责任原则

war*_*990 5 c# asp.net-mvc design-patterns entity-framework single-responsibility-principle

我有一个MVC项目,具有以下模式

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

例如,如果我的数据库中有2个表(Customer和Order),那么我的Repository层中有2个类(这个类映射1:1和我的数据库表,因为我使用的是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
}
Run Code Online (Sandbox Code Playgroud)

然后我有服务:

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
}
Run Code Online (Sandbox Code Playgroud)

你可能注意到我有GetCustomerOrders.

我的问题 :

  1. 不违反单一责任原则规则,我在哪里放GetCustomerOrders?在CustomerService,OrderService或两者兼而有之?

  2. 我是否通过在控制器中安装多个服务来违反单一责任原则规则?例如 :

     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
          }
     }
    
    Run Code Online (Sandbox Code Playgroud)
  3. 我有一堆控制器与膨胀的Action方法,例如我ProductController有:

     Index
     Add
     Edit
     Delete
     Priority
     AddPriority
     EditPriority
     DeletePriority
    
    Run Code Online (Sandbox Code Playgroud)

    如果控制器被拆分了

     ProductController
           Index
           Add
           Edit
           Delete
     ProductPriorityController
           Index
           Add
           Edit
           Delete
    
    Run Code Online (Sandbox Code Playgroud)

    我看到Microsoft的模板项目在他们的Controller中没有多个CRUD操作(对于底部示例).如果我的控制器内有多个CRUD操作(顶部示例),这是一个糟糕的设计吗?我正在考虑拆分我的控制器,但我不想让它在以后因为必须维护50个控制器而咬我的屁股.

任何帮助将不胜感激并为糟糕的英语道歉.

小智 0

  1. 我将把它放在 customerService 中,因为它取决于您传递给函数的客户。
  2. 我认为控制器的最大服务约为一个控制器中的约 3/4 服务。所以就你的情况我认为这很好。
  3. 控制器不需要实现您的业务逻辑。他们只应该获取数据并将其发布到正确的位置。我认为您应该创建一个管理器/服务/类来处理业务逻辑。关于您的 CRUD 操作,它应该全部在一个控制器中(获取/发布等)。