The Inversion of Control (IoC)
The Inversion of Control (IoC) and Dependency Injection (DI) patterns are all about removing dependencies from your code.
IoC is all about inverting the control. To explain this in layman's terms, suppose you drive a car to your work place. This means you control the car. The IoC principle suggests to invert the control, meaning that instead of driving the car yourself, you hire a cab, where another person will drive the car. Thus, this is called inversion of the control - from you to the cab driver. You don't have to drive a car yourself and you can let the driver do the driving so that you can focus on your main work.
For example, say your application has a text editor component and you want to provide spell checking. Your standard code would look something like this:
public class TextEditor { private SpellChecker checker; public TextEditor() { this.checker = new SpellChecker(); } }
What we've done here creates a dependency between the TextEditor
and the SpellChecker
because SpellChecker can be initiated whenever TextEditor class
will be called so TextEditor class directly depends on the SpellChecker class. This is also tight coupled code. We should make it loose coupling.
In other words, the Main class should not have a concrete implementation of an aggregated class, rather it should depend on abstraction of that class.
public class TextEditor { private IocSpellChecker checker; public TextEditor(IocSpellChecker 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. IOC can be done using Dependency Injection (DI). It explains how to inject the concrete implementation into a class that is using abstraction, in other words an interface inside.
Dependency Injection (DI)
The main idea of dependency injection is to reduce the coupling between classes and move the binding of abstraction and concrete implementation out of the dependent class. In Simple words, DI is how one object know about other dependent object which is abstracted.
To know more about Dependency Injection, please click here.