Inversion of Control IOC
What is Inversion Of Control
Inversion Of Control (IoC) is a design principle in which custom-written portions of a computer program receive the flow of control from a generic framework.
Delegate the function of selecting a concrete implementation type for the classes' dependencies to an external component or source.
What Real world Problem Are we trying to solve
You have classes that have dependencies on services or components whose concrete type is specified at design time. In this example, ClassA has dependencies on ServiceA and ServiceB. Following figure illustrates this.
This situation has the following problems:
- To replace or update the dependencies, you need to change your classes' source code.
- The concrete implementations of the dependencies have to be available at compile time.
- Your classes are difficult to test in isolation because they have direct references to dependencies. This means that these dependencies cannot be replaced with stubs or mocks.
- Your classes contain repetitive code for creating, locating, and managing their dependencies.
Solution
Delegate the function of selecting a concrete implementation type for the classes' dependencies to an external component or source.
How do we Implement this?
The Dependency Injection pattern and the Service Locator pattern are specialized versions of this pattern that delineate different implementations.
Dependency Injection
The Dependency Injection pattern uses a builder object to initialize objects and provide the required dependencies to the object.
Some examples of Dependency Injection
- Constructor injection
- Parameter injection
- Setter injection
- Interface injection
Service Locator
The Service Locator pattern introduces a locator object that objects use to resolve dependencies.
Other Implementation techniques for IOC
- Using a factory pattern
- Using a contextualized lookup
- Using template method design pattern
- Using strategy design pattern