asp.net-mvc - MVC DDD : Is it OK to use repositories together with services in the controller?

标签 asp.net-mvc model-view-controller architecture domain-driven-design

大多数时候在服务代码中我会有这样的东西:

public SomeService : ISomeService
{
    ISomeRepository someRepository;
    public Do(int id)
    {
        someRepository.Do(id);
    }
}

所以有点多余

所以我开始直接在 Controller 中使用存储库

这个可以吗 ?有没有这样的架构?

最佳答案

You lose the ability to have business logic in between.



我不同意这一点。

如果业务逻辑在它应该在的位置 - 在域模型中,那么在 Controller 中调用 repo(或者更好 - 使用模型绑定(bind)器)来获取聚合根并调用它对我来说似乎非常好。

当涉及太多技术细节时,应该使用应用程序服务,这会使 Controller 变得困惑。

I've seen several people mention using model binders to call into a repo lately. Where is this crazy idea coming from?



我相信我们在这里谈论的是两件不同的事情。我怀疑您的“模型绑定(bind)器”也意味着同时使用模型作为 View 模型,并将更改的值从 UI 直接绑定(bind)回它(这本身并不是一件坏事,在某些情况下我会走这条路)。

我的“模型绑定(bind)器”是一个实现“IModelBinder”的类',它在构造函数中获取存储库(如果我们需要使用一些基本组合进行缓存,则可以对其进行扩展)并在调用操作之前使用它来检索聚合根并替换 int idGuid idstring slugwhatever具有真实域对象的 Action 参数。将其与输入 View 模型参数相结合可以让我们编写更少的代码。像这样的东西:
public ActionResult ChangeCustomerAddress
 (Customer c, ChangeCustomerAddressInput inp){
  c.ChangeCustomerAddress(inp.NewAddress);
  return RedirectToAction("Details", new{inp.Id});
}

在我的实际代码中,它有点复杂,因为它包括 ModelState 验证和一些可能从域模型内部抛出的异常处理(提取到 Controller 扩展方法中以供重用)。但不多。到目前为止 - 最长的 Controller Action 大约是 10 行。

您可以看到有效的实现(非常复杂且(对我而言)不必要的复杂)here .

Are you just doing CRUD apps with Linq To Sql or trying something with real domain logic?



正如你可以(希望)看到的那样,这种方法实际上几乎迫使我们走向task based。应用程序而不是基于 CRUD 的应用程序。

By doing all data access in your service layer and using IOC you can gain lots of benefits of AOP like invisible caching, transaction management, and easy composition of components that I can't imagine you get with model binders.



...并拥有 的新抽象层诚邀 我们将基础设施与域逻辑混合在一起,失去了域模型的隔离。

Please enlighten me.



我不确定我是否做到了。我不认为我自己开悟了。 :)

Here是我当前的模型活页夹基类。 Here's我当前项目中的 Controller 操作之一。和here's “缺乏”业务逻辑。

关于asp.net-mvc - MVC DDD : Is it OK to use repositories together with services in the controller?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3574992/

相关文章:

ASP.NET MVC - jquery 日期选择器

java - 如何将信息从 servlet 传递到 JSP 页面

java - 使用 MVC 在 Java Web 应用程序中的过滤器中实现用户权限的正确方法是什么?

architecture - 多台服务器如何为 Web 应用程序同步工作?

php - 一个人修改的小网站,PHP序列化存储数据好吗

c# - 异步方法中的意外行为

c# - 将 EF5 升级到 EF 6,现在得到 "Cannot find the object because it does not exist or you do not have permissions."

c# - 在接口(interface)的实现中修改特定于类型的属性

c# - MVC 将 ViewBag 传递给 Controller

javascript - 更新记录时缺少可选字段值的正确明确的服务器端行为应该是什么?