您正在开发自己的 stackoverflow 版本:-)
您正在使用 ASP.NET MVC 和 Entity Framework (模型优先方法,如果重要的话)。因此,您有几个由 EF 生成的类:
class Question {...}
class Answer {...}
您还拥有所有相关内容( ObjectContext
等)。您拥有所有相关代码来处理回答问题的场景( StackoverflowController
和 AnswerQuestion
[get] + AnswerQuestion
[post] 操作,也是显示奇特表单的 View - 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());
}
}
但是您如何为这个逻辑命名正确的位置呢?它应该有什么接口(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);
}
}
您甚至可以将其分解为多个服务,例如 QuestionsService
、AnswersService
、UsersService
等。
关于c# - 业务逻辑的正确位置在哪里?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8316336/