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


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

查看所有标签

猜你喜欢:

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

人人都是产品经理2.0

人人都是产品经理2.0

苏杰 / 电子工业出版社 / 2017-5 / 66.6

《人人都是产品经理2.0——写给泛产品经理》继续定位在-1~3 岁的产品经理。这里特别要强调,“-1 岁”指的是“泛产品经理”群体,比如自认为是“产品新人”的“职场老人”,需要自己做产品的早期创业者,对产品感兴趣并且工作中可能要承担部分职责的技术、设计、运营等人员,其他行业对互联网产品感兴趣的从业者等,《人人都是产品经理2.0——写给泛产品经理》可以说是为他们量身定做的。 内容方面,《人人都......一起来看看 《人人都是产品经理2.0》 这本书的介绍吧!

Base64 编码/解码
Base64 编码/解码

Base64 编码/解码

URL 编码/解码
URL 编码/解码

URL 编码/解码

HEX HSV 转换工具
HEX HSV 转换工具

HEX HSV 互换工具