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

问题描述

Derik Whitaker发布了几天前,我点了一个点好奇一段时间:应该在控制器中存在业务逻辑吗



到目前为止所有的ASP.NET MVC演示我见过put repository访问和业务逻辑。有些甚至在那里也验证。这导致相当大的,,肿的控制器。这是真的使用MVC框架的方式吗?看来,这只是最终会有很多重复的代码和逻辑分散在不同的控制器。

解决方案

逻辑应该真正在模型中。



例如,不要有:

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

我宁愿有:

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

这假设税是由外部服务计算的,并且要求您的模型知道外部服务的接口。



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

  public class OrdersController {
public OrdersController 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 - 控制器中是否应该存在业务逻辑?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-14 07:13