c# - 业务逻辑的正确位置在哪里?

标签 c# .net asp.net-mvc entity-framework

您正在开发自己的 stackoverflow 版本:-)

您正在使用 ASP.NET MVC 和 Entity Framework (模型优先方法,如果重要的话)。因此,您有几个由 EF 生成的类:

class Question {...}
class Answer {...}

您还拥有所有相关内容( ObjectContext 等)。您拥有所有相关代码来处理回答问题的场景( StackoverflowControllerAnswerQuestion [get] + AnswerQuestion [post] 操作,也是显示奇特表单的 View - Stackoverflow/Answer )。

你的客户是一个非常强硬的人,所以他定义了一套业务规则:

  1. 在问题提出后的前 5 分钟内,任何人都不能回答问题(他们应该收到一条消息)。
  2. 发布答案后,主题发起者应该会收到通知。
  3. 主页应显示 20 个最新问题。
  4. 显示每个问题的答案时,应按投票排序。
  5. 当问题被否决的总分为 -10 时,应将其关闭。
  6. 当答案被否决的总数为 -10 时,他们的发帖者的声誉应获得 -20 的反奖励。

等等

问题是 - 鉴于上述事实,您将在哪里实现客户的业务规则?

我真的不喜欢这样的代码:

public class HomeController : Controller
{
    ...
    public ActionResult Index()
    {
        return View(_container.Questions.OrderByDescending(x => x.Posted).Take(20).ToList());
    }
}

但是您如何为这个逻辑命名正确的位置呢?它应该有什么接口(interface)?是不是这样的:

// implements the business logic, interacts with repositories
public static class Stackoverflow
{
    public static IEnumerable<Question> GetRecentQuestions() { ... } // logic here!
    public static void PostAnswer(Question question, Answer answer) { ... } // logic here!
}

最佳答案

一种解决方案是使用服务层来为您处理此问题:

public Interface IStackoverflowService
{
    IEnumerable<Question> GetRecentQuestions();
    void PostAnswer(Question question, Answer answer);
}

public class StackoverflowService : IStackoverflowService
{
    private StackoverflowDbContext _container;

    public StackoverflowService(StackoverflowDbContext container)
    {
        _container = container;
    }

    public IEnumerable<Question> GetRecentQuestions() 
    { 
         var model = _container.Questions.OrderByDescending(x => x.Posted);
         return model.Take(20);
    } 

    public void PostAnswer(Question question, Answer answer) { ... }
}

然后在你的 Controller 中:

public class HomeController : Controller
{
    private IStackoverflowService _stackoverflowService;

    public HomeController(IStackoverflowService stackoverflowService)
    {
        _stackoverflowService = stackoverflowService;
    }

    public ActionResult Index()
    {
        var model = _stackoverflowService.GetRecentQuestions();
        return View(model);
    }
}

您甚至可以将其分解为多个服务,例如 QuestionsServiceAnswersServiceUsersService 等。

关于c# - 业务逻辑的正确位置在哪里?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8316336/

相关文章:

c# - 引用 5MB .Net 程序集是否有任何性能注意事项?

.net - 如何将嵌入式 PowerShell 运行空间公开给远程处理

asp.net-mvc - 防火墙后面的服务器上的 Asp.Net MVC 应用程序的部署策略

c# - 如何通过提供方法名称作为字符串来模拟服务方法

c# - 获取绘制在窗口上的图像

c# - 如何在 C#.Net 中打开或启动 PDF 文件?

c# - 有什么方法可以影响 xaml 图标的样式吗?

.net - 具有多维数组的 Protobuf

java - 如何使用 Ajax.beginform + 部分 View 更新我的表,在 ym asp.net mvc Web 应用程序内部

c# - 从供应商的 Global.asax 继承 Global.asax 时,Application_Start 不会触发