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

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

问题描述

Derik Whitaker发表了一个文章中,令我好奇的一点大约有一段时间:控制器中应该有业务逻辑?



到目前为止,我看到的所有ASP.NET MVC演示都放置了存储库访问和控制器中的业务逻辑。有些甚至在那里抛出验证。这导致相当大的,膨胀的控制器。这真的是使用MVC框架的方式吗?看来,这样做最终将会导致不同控制器之间传播出很多重复的代码和逻辑。

解决方案

逻辑应该在模型中。你应该瞄准胖胖的模型,瘦的控制器。



例如,而不是:

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

我宁愿拥有:

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

这假设税收由外部服务计算,并要求您的模型了解您的外部服务的接口。



这将使您的控制器看起来像:

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

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

或类似的东西。


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?

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.

For example, instead of having:

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

I would rather have:

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);
    }
}

Or something like that.

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

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