Tuesday 12 July 2016

Inversion of control (IoC) and dependency injection

The Inversion of Control (IoC) and Dependency Injection (DI) patterns are all about removing dependencies from your code.

Example: Our application has a text editor component and we want to provide spell checking.

Our standard code would look something like this:
public class TextEditor {
       private SpellChecker checker;
       public TextEditor() {
              this.checker = new SpellChecker();
       }
}

What we've done here is create a dependency between the TextEditor and the SpellChecker.

In an IoC scenario we would instead do something like this:
public class TextEditor {
       private ISpellChecker checker;
       public TextEditor(ISpellChecker checker) {
              this.checker = checker;
       }
}

Now, the client creating the TextEditor class has the control over which SpellChecker implementation to use. We're injecting the TextEditor with the dependency.

It is a process whereby objects define their dependencies, that is, the other objects they work with, only through constructor arguments, arguments to a factory method, or properties that are set on the object instance after it is constructed or returned from a factory method.

The container then injects those dependencies when it creates the bean.
This process is fundamentally the inverse, hence the name Inversion of Control (IoC), of the bean itself controlling the instantiation or location of its dependencies by using direct construction of classes, or a mechanism such as the Service Locator pattern.

IoC containers:
1. BeanFactory
2. ApplicationContext

Dependency injection may happen through 3 ways:
1. Constructor injection.
2. Setter injection.
3. Interface injection

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...