MVC4理想控制器编码 [英] MVC4 Ideal controller coding

查看:96
本文介绍了MVC4理想控制器编码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我收到我的朋友的mvc4应用程序中,我将添加一些功能。但我发现他使用的控制器有超过6000线code的。
我想知道什么是开发MVC4应用程序的理想方式。

I recieved an mvc4 application from my friend in which I will add some functions. but I found that he use controllers with more Than 6000 line of code. I want to know what's the ideal way to develop MVC4 application.

指具有在每一行code数少很多控制器。还是有很大的数字线code的控制器数量少。

means to have many controllers with little number of line code in each one. or to have little number of controllers with big number of line code.

推荐答案

有绝对不是一个通用的解决这个问题,但是你可以通过使用存储库这也将让您减少的控制器内的线的数量尽量使用依赖注入模式的。

There definitely isn't a generic solution to this problem, however you can reduce the number of "lines" within a controller by using repositories which will also enable you to make use of the dependency injection pattern.

依赖注入也将有助于单元测试。该库中的逻辑分离到一个单独的(可更换)类。

Dependency injection will also help with unit testing. The repository separates the logic into a separate (replaceable) class.

搜索这些条款将提供大量的信息(不幸的是太多把所有的信息在一个SO问题) - 但是这里有一些code,将帮助您在正确的方向:

Searching these terms will provide lots of information (unfortunately far too much to put all the information in a SO question) – but here is some code that will help you in the right direction:

创建一个界面来定义库

public interface IGenericControllerRepository
{
    MyModel[] ComplexMethod();
}

Controller类:

Controller class:

public class GenericController : Controller
{
    private IGenericControllerRepository repository;

    public GenericController() : this(new GenericRepository()) { }

    public GenericController(IGenericControllerRepository genericRepository)
    {
        this.repository = genericRepository;
    }

    // GET: /controller
    public ActionResult Index()
    {
        MyModel[] m = repository.ComplexMethod();
        return View("Index", m);
    }
}

仓储类

public class GenericRepository : IGenericControllerRepository
{
    public MyModel[] ComplexMethod()
    {
        // do work here
    }
}

这是很难作为实际上取决于方法的数量,而不是线的数量(例如,你可以有数百个行数的方法)在这种情况下,分离来判断是否应该控制器分成较小的它们变成另一个控制器将不会获得所需的结果。你的控制器应分成应用程序逻辑容器。

It is hard to judge if you should split your controller into smaller ones as that really depends on the number of methods rather than the number of lines ( for example you could have a few methods with hundreds of lines ) in which case separating them into another controller won’t achieve a desired outcome. Your controllers should be split into "application logical" containers.

这篇关于MVC4理想控制器编码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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