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

发布于 2024-12-18 15:33:03 字数 1459 浏览 0 评论 0原文

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

幽梦紫曦~ 2024-12-25 15:33:03

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

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 等。

One solution is to use a service layer to handle this for you:

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

Then in your controller:

public class HomeController : Controller
{
    private IStackoverflowService _stackoverflowService;

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

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

You can even break it out into multiple services such as a QuestionsService, an AnswersService, a UsersService, etc.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文