What is Dependency Injection? [duplicate]

Possible Duplicate:
What is dependency injection?

Spring is the framework from where the concept Dependency Injection came to picture.

What is purpose of DI ? How does it benefit ? How is it implemented ?


Start here.

Also see A-beginners-guide-to-Dependency-Injection. (Obsolete)

Elsewhere on SO:

  • what-is-dependency-injection
  • dependency-injection-vs-factory-pattern
  • when-to-use-dependency-injection
  • difference-between-dependency-injection-and-inversion-of-control

What is the purpose of DI?

The purpose of Dependency Injection is to reduce coupling in your application to make it more flexible and easier to test.

How does it benefit?

Objects don't have hard coded dependencies. If you need to change the implementation of a dependency, all you have to do is Inject a different type of Object.

How does it implemented?

There are various methods of Dependency Injection. Check out the Wikipedia article to see examples of each. Once you understand those, you can start investigating the various Dependency Injection frameworks.


Very short,

What is the purpose of DI? With dependency injection, objects don't define their dependencies themselves, the dependencies are injected to them as needed.

How does it benefit ? The objects don't need to know where and how to get their dependencies, which results in loose coupling between objects, which makes them a lot easier to test.

How is it implemented ? Usually a container manages the lifecycle of objects and their dependencies based on a configuration file or annotations.