什么是业务逻辑的正确位置?

时间:2011-11-29 19:11:05

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

您正在使用自己的stackoverflow版本: - )

您正在使用ASP.NET MVC和实体框架(如果重要的话,模型优先方法)。所以,你有几个由EF生成的类:

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

您还拥有所有相关内容(ObjectContext等)。您拥有所有相关代码来处理回答问题的方案(StackoverflowController AnswerQuestion [get] + AnswerQuestion [post]操作,以及显示精美形式的视图 - { {1}})。

您的客户非常强硬,因此他定义了一套业务规则:

  1. 在提出问题后的前5分钟内,没有人能够回答这个问题(他们应该收到留言)。
  2. 发布答案时,主题入门者应收到通知。
  3. 主页应显示20个最新问题。
  4. 当显示每个问题的答案时,应该通过投票来订购。
  5. 如果问题总共被评为-10,则应该关闭它们。
  6. 当答案总数为-10时,他们的海报应该获得-20的反奖励。
  7. 问题是 - 鉴于上述事实,您将在何处实施客户的业务规则?

    我真的不喜欢使用代码的想法:

    Stackoverflow/Answer

    但是你如何为这个逻辑命名正确的地方?它应该有什么接口?它是这样的:

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

1 个答案:

答案 0 :(得分:3)

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

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) { ... }
}

然后在你的控制器中:

public class HomeController : Controller
{
    private IStackoverflowService _stackoverflowService;

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

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

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