ASP.NET MVC - 控制器中是否应该存在业务逻辑? [英] ASP.NET MVC - Should business logic exist in controllers?

查看:29
本文介绍了ASP.NET MVC - 控制器中是否应该存在业务逻辑?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Derik Whitaker 发布了一个 文章 几天前达到了我一直很好奇的一点大约有一段时间了:业务逻辑应该存在于控制器中吗?

Derik Whitaker posted an article a couple of days ago that hit a point that I've been curious about for some time: should business logic exist in controllers?

到目前为止,我看到的所有 ASP.NET MVC 演示都将存储库访问和业务逻辑放在控制器中.有些人甚至还会在那里进行验证.这会导致相当大的、臃肿的控制器.这真的是使用MVC框架的方式吗?看来这最终会导致大量重复的代码和逻辑分布在不同的控制器上.

So far all the ASP.NET MVC demos I've seen put repository access and business logic in the controller. Some even throw validation in there as well. This results in fairly large, bloated controllers. Is this really the way to use the MVC framework? It seems that this is just going to end up with a lot of duplicated code and logic spread out across different controllers.

推荐答案

业务逻辑确实应该在模型中.你应该瞄准胖模型,瘦控制器.

Business logic should really be in the model. You should be aiming for fat models, skinny controllers.

例如,而不是:

public interface IOrderService{
    int CalculateTotal(Order order);
}

我宁愿:

public class Order{
    int CalculateTotal(ITaxService service){...}        
}

这假设税收是由外部服务计算的,并且需要您的模型了解与外部服务的接口.

This assumes that tax is calculate by an external service, and requires your model to know about interfaces to your external services.

这会让你的控制器看起来像:

This would make your controller look something like:

public class OrdersController{
    public OrdersController(ITaxService taxService, IOrdersRepository ordersRepository){...}

    public void Show(int id){
        ViewData["OrderTotal"] = ordersRepository.LoadOrder(id).CalculateTotal(taxService);
    }
}

或者类似的东西.

这篇关于ASP.NET MVC - 控制器中是否应该存在业务逻辑?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆