What is dependency injection and why would I want to use it?

Possible Duplicate:
What is dependency injection?

Other developers on my team keep talking about dependency injection. I have looked it up on Wikipedia but I still don't understand exactly what it is or when I would want to use it in my designs. If you have any good examples of when you have used it or when you shouldn't that would really help me out. Thanks


The basic idea is that when an object needs some other other to do it's work (say for example, a database connection), instead of creating that object internally, the object is "injected" into the object, usually either as a constructor parameter, or by a public property that is set before the object is used.

The advantage of that is that the value of the used object can be changed externally (this is especially true if the object is declared as an interface). One common use of this is to replace concrete object with mock object for unit testing.


Another term of reference which might be of assistance is "Inversion of Control".

Rather than constructing your software with dependencies and assumptions about the libraries you will continue to use with that application forever, IoC or DI allow you to specify an interface which must be satisfied by some other component, then at runtime supply a mapping of interface-satisfying components for the executing application (usually in a service container which provides the IoC satisfying service as some variety of service-resolution service).

This abstraction allows you to more readily replace an implementation which no longer meets your organization's needs with a new version, or even an entirely new backing technology, with a smaller footprint of change and thus lower risk.

Castle Windsor is one .Net implementation of an IoC container.


You might find this article useful in understanding this whole idea.

The idea is to help you decouple your clases so that each individual class can be used or tested independently.

链接地址: http://www.djcxy.com/p/14404.html

上一篇: 依赖注入设计模式

下一篇: 什么是依赖注入,为什么我要使用它?