什么地方适合放置业务逻辑?
本文关键字:业务 什么地方 | 更新日期: 2023-09-27 18:16:12
您正在开发自己版本的stackoverflow:-)
你正在使用ASP。. NET MVC和实体框架(如果重要的话,采用模型优先的方法)。所以,你有两个类由EF生成:
class Question {...}
class Answer {...}
你也有所有相关的东西(ObjectContext
等)。您拥有所有相关代码来处理回答问题的场景(StackoverflowController
与AnswerQuestion
[get] + AnswerQuestion
[post]动作,还有一个视图来显示一个花哨的表单- Stackoverflow/Answer
)。
你的客户是一个非常强硬的人,所以他定义了一组业务规则:
- 在提问后的前5分钟内没有人能够回答问题(他们应该得到一个消息)。
- 当答案发布后,话题发起者将收到通知。
- 主页面应该显示20个最新的问题。
- 当显示每个问题的答案时,他们应该按投票排序。
- 当问题被否决的总数为-10时,他们应该被关闭。
- 当答案被拒绝的总数为-10时,他们的海报应该得到-20的反奖励。
等。
问题是——给定上述事实,您将在哪里实现客户的业务规则?
我真的不喜欢这样的代码:
public class HomeController : Controller
{
...
public ActionResult Index()
{
return View(_container.Questions.OrderByDescending(x => x.Posted).Take(20).ToList());
}
}
但是你怎么命名这个逻辑的正确位置呢?它应该有什么样的界面?是这样的吗?
// 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) { ... }
}
然后在控制器中:
public class HomeController : Controller
{
private IStackoverflowService _stackoverflowService;
public HomeController(IStackoverflowService stackoverflowService)
{
_stackoverflowService = stackoverflowService;
}
public ActionResult Index()
{
var model = _stackoverflowService.GetRecentQuestions();
return View(model);
}
}
您甚至可以将其分解为多个服务,例如QuestionsService
, AnswersService
, UsersService
等