Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
578 views
in Technique[技术] by (71.8m points)

design patterns - ASP.NET MVC - Should business logic exist in controllers?

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.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...