Dependency Injection

Revision as of 03:09, 3 June 2018 by Rasimsen (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

What is Dependency Injection?

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 rather than by the objects themselves.

Here’s how you would create an object dependency in traditional programming:

public class Store {
    private Item item;
  
    public Store() {
        item = new ItemImpl1();    
    }
}

In the example above, we need to instantiate an implementation of the Item interface within the Store class itself.

By using DI, we can rewrite the example without specifying the implementation of Item that we want:

public class Store {
    private Item item;
    public Store(Item item) {
        this.item = item;
    }
}