Dependency Injection



Table of Contents

Definition

Inversion of Control is a principle in software engineering by which the control of objects or portions of a program is transferred to a container or framework

  • decoupling the execution of a task from its implementation
  • making it easier to switch between different implementations
  • greater modularity of a program
  • greater ease in testing a program by isolating a component or mocking its dependencies and allowing components to communicate through contracts

Dependency Injection

Inversion of Control can be achieved through various mechanisms such as:

  • Strategy design pattern,
  • Service Locator pattern
  • Factory pattern
  • Dependency Injection (DI).

Injecting Objects

Dependency injection is a pattern through which to implement IoC, where the control being inverted is the setting of object's dependencies.

The act of connecting objects with other objects, or “injecting objects" into other objects, is done by an assembler instead of the objects themselves.

Create an object dependency in traditional programming:
public class Store {
    private Item item;
    public Store() {
        item = new ItemImpl1();    
    }
}
By using DI
public class Store {
    private Item item;
    public Store(Item item) {
        this.item = item;
    }
}