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

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

问题描述

我是MVC的新人,但从迄今为止所学到的知识(例如这里,由ScottGu)应该向瘦的控制者而不是胖的人

添加到事实上,视图本身就很薄,你会在模型中获得很多的代码。



所以我的问题是 - 如何将模型中的代码分成不同的逻辑部分,以减少复杂性?

您是否使用数据访问层和业务逻辑层在模型本身(我猜想仍然会拥有很多代码),还是有更好的方法?



谢谢。

解决方案

我们使用的图层是: / p>


  • 查看(带强类型的查看模型)

  • 控制器

  • 查看模特服务

  • 商务服务

  • 存储库

  • (EF)上下文



视图 - 尽可能薄 - 无逻辑 - 只显示



查看模型 - 强力键入每个视图 - 不包含实体,只是我们想要的任何一个视图中的字段。



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



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



业务服务 - 主要数据访问点。每个控制器一个BS。使用所需的许多存储库来完成工作。交易范围控制器。 VMS对BS进行单一呼叫 - 如果需要,将单个事务中的所有必需的数据库调用包装起来。我们预计未来BS将呼叫外部服务。



存储库 - 一个(顶级)实体 - 对一组实体执行所有CRUD操作。我们的实体是大型,复杂的对象图,所以我们处理每个存储库中最顶层的父类。



上下文 - 围绕EF生成的上下文的薄包装,所以他们可以嘲笑。



在MVC方面 - 模型部分由控制器下面的所有内容组成。


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?

Thank you.

解决方案

The layers we use are:

  • View (with strongly typed View Models)
  • Controller
  • View Model Service
  • Business Services
  • Repositories
  • (EF) Contexts

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.

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

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.

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.

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.

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

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

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

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