What is Dependency Injection

Definition
Precisely, Wikepedia says

Dependency injection is a software design pattern that allows a choice of component to be made at run-time rather than compile time. This can be used, for example, as a simple way to load plugins dynamically or to choose mock objects in test environments vs. real objects in production environments.

Let’s break the term to understand it further.

What is Dependency? What is Injection?
Assignment of a instance variable to a reference is dependency injection. The reference variable involved is known as dependency. For example: consider a base class Car. Also consider a child class named Mercedes which is derived from Car. And reference variable of class Car as mercedesCar which is defined as:

class CarSelector
    {
        Car mercedesCar = null;

        public CarSelector()
        {
            
        }
    }

The variable mercedesCar is dependency.
Now later in the code, whenever we assign a instance variable to the reference mercedesCar by passing value through constructor, we are actually doing injection of dependency.

class CarSelector
    {
        Car mercedesCar = null;

        public CarSelector(Mercedes NewMercedes)
        {
            mercedesCar = NewMercedes;
        }
    }

Need of Dependency Injection Pattern
Code given above is tightly coupled to class Mercedes. What if we wanted to give option of selection of a car of any make, that too by just a change of a simple config file. This is a problem which the Dependency Injection pattern solves. DI pattern coupled with Factory Pattern will make code extensible to a very large extent.

A practical implementation is choice of database with a change in config file. Another scenario is instead of passing actual objects, Mock objects can be passed which is extremely helpful in testing.

References and Further Reading:
Just a simple Google query and it will return loads of articles explaining the concept of Dependency injection.

  1. I would say if you are extremely good in design patterns then head over straight to Martin Fowler’s Inversion of Control Containers and the Dependency Injection pattern.
  2. However the best and the simplest explanation of DI is written by James Shore: Dependency Injection Demystified.
  3. MSDN Magazine’s Dependency Injection refresher

This post also provided the answer to dependency injection question in the post latest dot net interview questions

DZoneDeliciousLinkedInRedditTechnorati FavoritesStumbleUponShare

4 comments

  1. [...] Answer A brief introduction to dependency injection. [...]

  2. What is Dependency Injection…

    You’ve been kicked (a good thing) – Trackback from DotNetKicks.com…

  3. JavaPins says:

    What is Dependency Injection | Tech Samosa…

    Thank you for submitting this cool story – Trackback from JavaPins…

  4. Nice explanation of dependency injection

Leave a Reply

Your email address will not be published. Required fields are marked *