Difference between revisions of "Dependency Injection"

(Created page with "==='''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 depe...")
 
 
Line 29: Line 29:
 
}
 
}
 
</source>
 
</source>
 
In the next sections, we’ll see how we can provide the implementation of Item through metadata.
 
 
Both IoC and DI are simple concepts, but have deep implications in the way we structure our systems, so they’re well worth understanding well.
 

Latest revision as of 03:09, 3 June 2018

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;
    }
}