将模型代码划分为 MVC 中的逻辑部分的最佳实践?哪个最好? [英] Best practices to partition Model code to logical parts in MVC? Which is the best?

查看:27
本文介绍了将模型代码划分为 MVC 中的逻辑部分的最佳实践?哪个最好?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 MVC 的新手,但从我到目前为止学到的东西(例如 此处,作者 ScottGu)应该追求瘦控制器"而不是胖"控制器.
再加上视图本身就很薄的事实,您将在模型中获得大量的代码.

I'm new to MVC but from what I have learned so far (for example here, by ScottGu) one should aspire to "skinny controllers" rather than "fat" ones.
Add to that the fact that views are inherently thin, and you'll get a lot of code in your model.

所以我的问题是 - 您如何将模型中的代码划分为不同的逻辑部分以降低复杂性?
您是否在模型本身中使用了数据访问层和业务逻辑层(我猜这仍然会包含大量代码),或者是否有更好的方法来做到这一点?

So my question is - How do you partition the code in your model to different logical parts in order to reduce complexity?
Do you use Data Access Layer and Business Logic Layer within the model itself (which I guess would still hold a lot of code), or are there better ways of doing that?

谢谢.

推荐答案

我们使用的层是:

  • 视图(使用强类型视图模型)
  • 控制器
  • 查看模型服务
  • 商业服务
  • 存储库
  • (EF) 上下文

视图 - 尽可能薄 - 没有逻辑 - 只是显示

Views - as thin as can be - no logic - just display

视图模型 - 每个视图都是强类型的 - 不包含实体,而只包含我们想要在任何一个视图中显示的字段.

View Models - Strongly typed per view - don't contain Entities, but just the fields we want in any one view.

控制器 - 只是路由和调用 VMS.通过路由到错误页面来处理从较低级别冒出的异常.

Controller - just routing and calls to VMS. Handles exceptions that bubble up from the lower levels by routing to error pages.

视图模型服务 - 创建视图模型并将其解包到 EF 实体中.没有数据访问逻辑.每个控制器一个 VMS.大量使用 AutoMapper 将视图模型的数据传输到实体中.

View Model Services - creates and unpacks view models into the EF entities. No data access logic. One VMS per controller. Makes heavy use of AutoMapper to transfer the view model's data into entities.

业务服务 - 数据访问的主要点.每个控制器一个 BS.根据需要使用尽可能多的存储库来完成其工作.事务范围控制器在这里.VMS 对 BS 进行一次调用 - 如果需要,BS 将所有必要的 DB 调用包装在单个事务中.我们预计 BS 将来会调用外部服务.

Business Services - main point of data access. One BS per controller. Uses as many repositories as required to do its job. Transaction scope controller here. The VMS makes a single call to the BS - which wraps all the necessary DB calls in a single transaction if required. We anticipate the BS making calls out to external services in future.

存储库 - 每个(顶级)实体一个 - 为一组实体执行所有 CRUD 操作.我们的实体是大型、复杂的对象图 - 因此我们处理每个存储库的最顶层父级.

Repositories - One per (top level) entity - does all CRUD operations for a group of entities. Our entities are large, complex object graphs - so we handle the top-most parent per repository.

上下文 - 围绕 EF 生成的上下文的薄包装器,以便我可以嘲笑它们.

Contexts - thin wrappers around the EF generated contexts so they can me mocked.

就 MVC 而言 - 模型部分由控制器下方的所有内容组成.

In terms of MVC - The Model part is made up of everything below the controller.

这篇关于将模型代码划分为 MVC 中的逻辑部分的最佳实践?哪个最好?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆