Bits N Tricks

Inversion of Control (IoC) and Dependency Injection (DI)

“Inversion of Control is a generic design principle of software architecture that assists in creating reusable, modular software frameworks that are easy to maintain.”

It is a design principle in which the Flow of Control is “received” from the generic-written library or reusable code.

To understand it better, in procedural/traditional languages, the business logic generally controls the flow of the application and “Calls” the generic or reusable code/functions. For example, In a simple Console application, my flow of control is controlled by my program’s instructions, that may include the calls to some general reusable functions.
In Contrast, in IoC, Frameworks are the reusable code that “Calls” the business logic.

For example, in a windows based system, a framework will already be available to create UI elements like buttons, menus, windows and dialog boxes. When I write the business logic of my application, it would be framework’s events that will call my business logic code (when an event is fired) and NOT the opposite.

Although, the framework’s code is not aware of my business logic, it will still know how to call my code. This is achieved using events/delegates, callbacks etc. Here the Control of flow is “Inverted”.

We’ll see a more detailed example in a while.

IoC is also known as “Hollywood Principle” with its essence in the statement “Don’t call us, we’ll call you” relating to the response a budding actor might hear after auditioning for a role.

So, instead of depending the flow of control on statically bound objects, the flow depends upon the overall object graph and the relations between different objects.

Inversion of Control can be achieved using various techniques like

Callbacks

Observer Pattern (Also the base for delegation and eventing)

Factory Pattern

Dependency Injection

and many more.

Next, we are going to have a look at one of the ways to achieve IoC i.e. Dependency Injection (DI).

In simpler words, when you are trying to write code, you will be creating and using different classes. One class (Class A) may use other classes (Class B and/or D). So, Class B and D are dependencies of class A.

A simple analogy will be a class Car. A car might depend on other classes like Engine, Tyres and more.

Dependency Injection suggests that instead of the Dependent classes (Class A here) creating its dependencies (Class B and class D), the class (Class A) should be injected with the concrete instance of the dependency.

Lets understand with a more practical example. Consider that you are writing your own TextEditor. Among other things, you can have a spellchecker that provides the user with a facility to check the typos in his text. A simple implementation of such a code can be:

At first sight, everything looks rosy. The user will write some text. The developer will capture the text and call the CheckSpellings function and will find a list of Typos that he will show to the User.

Everything seems to work great until one fine day when one user starts writing French in the Editor.

Well. we can now either have a simple excuse that our Text Editor does not work with any language other than English. Or we can try to extend the Editor to support more languages.

To provide the support for more languages, we need to have more SpellCheckers.
Probably French, German, Spanish etc.

Here, we have created a tightly-coupled code with “English”SpellChecker being tightly coupled with our TextEditor class, which means our TextEditor class is dependent on the EnglishSpellChecker or in other words EnglishSpellCheker is the dependency for TextEditor. We need to remove this dependency. Further, Our Text Editor needs a way to hold the concrete reference of any Spell Checker based on developer’s discretion at run time. Polymorphism to the rescue.

We can create an Interface ISpellChecker like

interface ISpellChecker
{
Arraylist CheckSpelling(string Text);
}

Please note that we now need to pass the string to scan, as a parameter. When the Spellchecker was coupled with the TextEditor, it could get the Text from the property of the class.

Now, to instantiate the SpellChecker type, we can either write the constructor to have the logic of switching between different SpellCheckers based on a parameter like “string language”, OR move that logic to a totally separate Factory class that will instantiate the correct type, something like

Hmmm, After making this mammoth effort, have we been able to remove the dependency from our code? Well, Not really. Although, we might have been able to loose the coupling between the TexEditor and the SpellChecker, we have introduced a new Dependency – The SpellFactory, which might not sound bad, however, we can definitely bump in a situation where we might need more generic code for this factory, probably for different types and families of the SpellCheker.

Dependency Injection – The Finale

So, as we saw in the introduction of DI, it suggests that the class should be injected with its dependencies. So, it should be the calling code’s responsibility to inject all the dependencies to the called class/code. In our example, the TextEditor class should receive the concrete instance of ISpellChecker type.

Now, the dependency can be injected in Constructor, a Public Property or a method.