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

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

问题描述

Derik惠特克的发布<一个href=\"http://devlicio.us/blogs/derik_whittaker/archive/2008/10/22/how-is-interacting-with-your-data-repository-in-your-controller-different-or-better-than-doing-it-in-your-$c$c-behind.aspx\">article一对夫妇日前袭击,我一直好奇了一段时间点:应业务逻辑控制器存在

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框架的方法吗?看来,这仅仅是将有很多重复的code和不同的控制器逻辑US $ p $垫出落得。

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

或者类似的东西。

Or something like that.

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

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