Dependency Injection

Injecting an instance of a class into a class that depends on it, is called Dependency Injection.

Dependency Injection is of 2 types.
  1. Constructor InjectionConstructor Injection, ensures that all the dependency objects are initialized before we attempt to invoke any methods or peroperties, thus avoiding null reference exceptions.
  2. Setter InjectionSetter Injection, enables you to inject the object, just before you need it. So, if the object is an expensive object to create, and you want to create it as late as possible
What are the advantages of using Dependency Injection?
  1. Dependency Injection allows us to develop very loosely coupled systems.
  2. Easy to swap in a different implementation of a component, as long as the component implements the interface type.
  3. Dependency Injection, allows objects to be mocked with in the Unit Tests. This is the greatest advantage of Dependency Injection.
Source & Example: http://venkataspinterview.blogspot.com/2011/06/explain-dependency-injection-with.html