Oct 16, 2015

Dependency Injection (DI) vs. Inversion of Control (IOC)

The main goal of Inversion of control and Dependency Injection is to remove dependencies of an application. This makes the system more decoupled and maintainable.
First let’s try to understand IOC (Inversion of control). If you go back to old computer programming days, program flow used to run in its own control. For instance let’s consider a simple chat application flow as shown in the below flow diagram.
  1. End user sends chat message.
  2. Application waits for the message from the other end.
  3. If no message is found it goes to Step 2 or else moves to Step 4.
  4. Displays the message.
  5. User continues with his work ahead.
Now if you analyze the program flow closely, it’s sequential. The program is in control of himself. Inversion of control means the program delegates control to someone else who will drive the flow. For instance if we make the chat application event based then the flow of the program will go something as below:-
  1. End user sends chat message.
  2. User continues with his work ahead.
  3. Application listens to events. If a message arrives event is activated and message is received and displayed.
If you see the program flow it’s not sequential, its event based. So now the control is inverted. So rather than the internal program controlling the flow, events drive the program flow. Event flow approach is more flexible as their no direct invocation which leads to more flexibility.

IOC (Inversion of control) is a general parent term while DI (Dependency injection) is a subset of IOC. IOC is a concept where the flow of application is inverted. So for example rather than the caller calling the method.

 

Inversion of control :- It’s a generic term and implemented in several ways (events, delegates etc).
Dependency injection :- DI is a subtype of IOC and is implemented by constructor injection, setter injection or method injection.

No comments:

Post a Comment