【问题标题】:Design pattern: bundle models in controller or in service设计模式:在控制器或服务中捆绑模型
【发布时间】:2015-10-02 15:52:16
【问题描述】:

我们使用带有实体框架的 asp.net mvc 作为我们的 ORM。

我们的数据库真的很旧,而且是很久以前建立的。所以外键丢失了,我们现在不能添加它。我们需要将不同的模型捆绑到 ViewModel 中。我们不确定是否应该在不同的服务方法或控制器中进行初始模型捆绑。

所以我的问题是你认为最好的设计模式和实践。 捆绑在控制器中:

 public class PlayerController : ApiController
 {
     private readonly IPlayerService _playerService;
     private readonly IItemService _itemService;

     public PlayerController(IPlayerService playerService, IItemService itemService)
     {
         _playerService = playerService;
         _itemService = itemService;
     }


     public UserViewModel Get(int id)
     {
        var user = playerService.GetUser(id);
         var item = itemService.GetItem(id);
         var userViewModel = Mapper.Map<UserViewModel(user);
         userViewModel.item = Mapper.Map<ItemViewModel(item);
         return userViewModel;
     }
 }

或捆绑在服务中:

public class PlayerController : ApiController
 {
     private readonly IPlayerService _playerService;
     private readonly IItemService _itemService;

     public PlayerController(IPlayerService playerService, IItemService itemService)
     {
         _playerService = playerService;
         _itemService = itemService;
     }


     public UserViewModel Get(int id)
     {
        var userWithItem = playerService.GetUserWithItem(id);
        return Mapper.Map<UserViewModel(userWithItem);
     }
 }

获取项目的调用将在“GetUserWithItem”中完成,如下所示:

public User GetUserWithItem(int id)
{
    var user = _dbContext.user.Find(id);
    user.Item = _dbContext.item.Where(x=>x.userId => id);

    return user;
}

哪种“正确”的做法会带来最大的好处?

【问题讨论】:

  • 未知数太多,不知道哪个是“正确的”。我使用的快速经验法则...您是否需要在多个控制器中使用给定的视图模型?如果是这样,我倾向于在服务层中进行繁重的工作。如果仅在一个控制器中需要视图模型,我倾向于在控制器中完成工作。话虽如此,我倾向于使用非常薄的控制器。不喜欢将代码埋在难以重用和测试的地方。
  • 我更喜欢让控制器尽可能地薄。在这种情况下,我什至会将 UserViewModel Get(int id) 方法从控制器移到服务或特殊 UI 层。
  • 我更喜欢每个操作方法调用一个服务,然后将其留给服务层(及其他层)来将数据制定为适当的模型。当我有所不同时,只有当它是真正特定于 UI 的东西时,它才会出现在模型部件上,例如 SelectList 项目。在这种情况下,服务将传递数据(一次调用),控制器可以完成额外的工作,将其翻译成与视图相关的适当格式。
  • @IlyaChumakov 一般来说,我认为 ViewModel 不应该离开控制器层。这是关于将您不想与前端通信的数据分开。

标签: c# asp.net asp.net-mvc design-patterns


【解决方案1】:

第二种方法看起来比第一种方法好得多。让控制器尽可能轻便。

建议,应该通过抽象而不是实现来公开依赖项。您应该通过接口引入抽象,而不是使用PlayerServiceItemService 的具体类。在构造函数注入中使用IPlayerServiceIItemService

【讨论】:

  • 感谢您的回答。它们是接口,只是我很快写了这个问题。已编辑。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-29
  • 2010-10-02
  • 2011-09-11
  • 1970-01-01
  • 1970-01-01
  • 2014-01-27
相关资源
最近更新 更多