IoC Introduction

Education is not limited to just classrooms. It can be gained anytime, anywhere... - Ravi Ranjan (M.Tech-NIT)

The terms Inversion of Control (IoC), Dependency Injection Principle (DIP), Dependency Injection (DI), and IoC containers may be familiar. But are you clear about what each term means?

Here, you are going to learn about each term, with simple and real-world examples to clear your confusion. Before you go further, it is important to understand the difference between principle and pattern.

Now, let's understand the above buzz words. The following figure clears the confusion whether on they are principles or patterns.

As illustrated in the above figure, IoC and DIP are high level design principles which should be used while designing application classes. These are principles, so they only recommend certain best practices but do not provide any specific implementation details. Dependency Injection (DI) is a pattern and IoC container is a framework.

Let's have an overview of each before going into details.

Inversion of Control:

IoC is a design principle which recommends inversion of different kinds of controls in object oriented design to achieve loose coupling between the application classes. Here, the control means any additional responsibilities a class has other than its main responsibility, such as control over the flow of an application, control over the dependent object creation and binding (Remember SRP-Single Responsibility Principle). If you want to do TDD (Test Driven Development) then you must use IoC principle without which TDD is not possible. Learn about IoC in detail in the next chapter.

Dependency Inversion Principle:

DIP principle also helps in achieving loose coupling between the classes. It is highly recommended to use DIP and IoC together in order to achieve loose coupling.

DIP suggests that high-level modules should not depend on low level modules. Both should depend on abstraction.

DIP principle is invented by Robert Martin (a.k.a. Uncle Bob). He is a founder of SOLID principles. Learn about DIP in the DIP chapter.

Dependency Injection:

Dependency Injection (DI) is a design pattern which implements IoC principle to invert the creation of dependent objects. We will learn about it in the DI chapter.

IoC Container:

The IoC container is a framework to manage automatic dependency injection throughout the application so that we as a programmer do not need to put more time and effort on it. There are various IoC Containers for .NET such as UnityNinjectStructureMapAutofac etc. We will learn more about it in the IoC Container chapter.

We cannot achieve loosely couplde classes by only using IoC. Along with IoC we also need to use DIP, DI and IoC container. The following figure illustrates how we are going to achieve loosely coupled design step by step in the next few chapters.

Let's learn about each of the above steps, starting with IoC as the first step in the next chapter.