c# – Controller中带参数的构造函数 – MVC

栏目: 后端 · 发布时间: 7年前

内容简介:翻译自:https://stackoverflow.com/questions/15332159/constructor-with-parameter-in-controller-mvc

我读过很多关于IOC和Unity的文章,让我感到困惑:(

所以回到基础可以告诉我以下代码的作用吗?

private IStudent _student;
public HomeController(IStudent student)
{
     _student= student;
}

public interface IStudent 
{
     // Some method
}

Itz Basic,但我试图从外行的角度来理解.上面的代码到底是做什么的?

HomeController依赖于Student,因为它将一些责任委托给Student类.

一种实施方式是:

public HomeController()
{
    private Student _student;
    public HomeController()
    {
        _student = new Student();
    }
}
public class Student 
{
    // Some method
}

但是HomeController对Student class有很强的依赖性.如果您想使用Student的其他实现(例如,想要在对HomeController进行单元测试时模拟Student),该怎么办?您将不得不修改Student类或HomeController类(或使用其他一些不那么好的选项).这意味着您的HomeController与Student类紧密耦合.

另一种方式是您发布的代码:

public class HomeController
{
    private IStudent _student;
    public HomeController(IStudent student)
    {
        _student = student;
    }
}
public interface IStudent
{
    // Some method
}
public class Student : IStudent
{
    // Implementation of some method
}

在这里,您可以传递IStudent的任何实现,即在您的单元测试中,您可以传递IStudent的模拟对象,在您的实际代码中,您将传递Student类的对象.所以你HomeController现在依赖于IStudent接口(抽象)而不是Student类(一个实现).

这符合OOP原则:

Program to interfaces, not implementations.
Depend on abstractions. Do not depend on concrete classes.

此外,它现在具有软依赖性.它不再与Student课程紧密耦合.它松散耦合.

现在,通常您不必担心在实例化HomeController时应该通过哪个IStudent实现.只要您使用它注册正确的接口和类,这就是Depedency Injection Container(在您的情况下为Unity)将要处理的事情.

_container.Register<IStudent, Student>();

因此,当需要HomeController的新实例时,容器将识别需要IStudent的实例.因此,它将实例化IStudent的已注册实例,并在实例化HomeController类时将其作为参数传递.

另请注意,您所指的是“依赖注入”(这是IoC的一种特定形式).还有其他形式的IoC(例如回调,观察者模式等).

编辑:

不要忘记阅读DI上的 popular article .

翻译自:https://stackoverflow.com/questions/15332159/constructor-with-parameter-in-controller-mvc


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Web Designer Idea

Web Designer Idea

梁景红 / 电子工业出版社 / 2006年 / ¥55.00

这是一本以“目的、信息、设计、创意”作为根脉的关于网页视觉的书籍,畅谈的话题从策划到编辑再到设计,从而讨论“我们要建立怎样的站点,并以何种形式完成它”的问题。 全书共分四个部分,分别是网站建设目的,网站信息内容,页面形式设计,网页创作构思。 四部分有机地结合,形成一个统一的整体。“目的”部分以建设网站的目的为主,带领设计师从建站目的的角度,探讨如何抓住首要问题;如何建立网站雏形;如何打开狭隘的、局......一起来看看 《Web Designer Idea》 这本书的介绍吧!

RGB转16进制工具
RGB转16进制工具

RGB HEX 互转工具

XML、JSON 在线转换
XML、JSON 在线转换

在线XML、JSON转换工具

RGB HSV 转换
RGB HSV 转换

RGB HSV 互转工具