HomeController中对学生一个依赖,因为它代表了一些责任Student类。实施
一种方法是:
public HomeController()
{
private Student _student;
public HomeController()
{
_student = new Student();
}
}
public class Student
{
// Some method
}
但随后的HomeController对学生类硬依赖。如果你想使用学生的其他实现(例如想要在单元测试HomeController的时候模拟学生),该怎么办?你将不得不修改学生类或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接口(抽象)而不是在学生类(一个实现)。 这符合OOP原则:
编程为接口,而不是实现。
取决于抽象。不要依赖于具体的课程。
此外,它现在具有软依赖性。它不再与Student类紧密结合。它是松耦合。 现在,通常您不需要担心在实例化您的HomeController时应该通过哪个IStudent实现。这就是Depedency Injection Container(你的情况下的Unity)会照顾到的,只要你注册了正确的接口和类。
_container.Register<IStudent, Student>();
因此,当需要一个新的HomeController实例时,容器将识别需要一个IStudent实例。因此它将实例化IStudent的注册实例,并在实例化HomeController类时将其作为参数传递。
此外,请注意您所指的是'依赖注入'(这是IoC的一种特定形式)。还有其他形式的IoC(例如回调,观察者模式等)。
编辑: 不要忘了阅读DI上的popular article。
这是[Dependency Injection](http://martinfowler.com/articles/injection.html)的[构造函数注入](http://martinfowler.com/articles/injection.html#injector.gif)风格。 – publicgk 2013-03-11 06:11:38