内容简介:翻译自: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版)
[美] Thomas H.Cormen、Charles E.Leiserson、Ronald L.Rivest、Clifford Stein / 潘金贵 等 / 机械工业出版社 / 2006-9 / 85.00元
这本书深入浅出,全面地介绍了计算机算法。对每一个算法的分析既易于理解又十分有趣,并保持了数学严谨性。本书的设计目标全面,适用于多种用途。涵盖的内容有:算法在计算中的作用,概率分析和随机算法的介绍。书中专门讨论了线性规划,介绍了动态规划的两个应用,随机化和线性规划技术的近似算法等,还有有关递归求解、快速排序中用到的划分方法与期望线性时间顺序统计算法,以及对贪心算法元素的讨论。此书还介绍了对强连通子图......一起来看看 《算法导论(原书第2版)》 这本书的介绍吧!