Concept of Dependency Injection (DI)

Dependency Injection (DI) is a coding design pattern and implementation of Inversion of control (IoC) like Service Locator and Abstract Factory. We can use DI in any programming language for example JavaScript, C#, JAVA etc… Main purpose of dependency injection is optimized the code and make code as efficient, reusable and testable (by unit test). DI uses for decoupling the objects and reduce the dependency.

Tightly & Loosely coupled:

Object are created by the class and if class is depended on other class(es) or object(s) that means it is a tight coupling and it would be create trouble in future if changes is occur in depended class. Because programmer need to change in main class too and that’s why using tightly coupled code style is a bad practice.

In above code if we want glasses color too then programmer add this option in Glasses class and also change in Human class. Changes would be as following:

Now, we want human wearing colored lenses. So, programmer will add new class “Lenses” and also will change in Human class. New created class “Lenses” as following

Now, we want human wearing VR BOX!!! So, programmer will add new class VRBOX and will change in Human class too. That means Human class will change every time. So, programmer need to change is design pattern and convert the Human tight coupling with Glasses, Lenses and VRBOX into loose coupling. Programmer has three options to deploy the DI.

  • Constructor Injection
  • Method Injection
  • Property Injection

Now, Human object will not create the dependency. We are going to use Constructor Injection with Interface implementation.

By applying the Dependency Injection, programmer convert the tight coupling into loosely coupling (decoupling).


By using the DI, code becomes very flexible, hard-coded free, testable (Unit test) and understandable.

Unit Testing:

IoC Frameworks for .Net: