Articles

Importance of Dependency Injection in ASP.NET MVC 5-6

Dependency Injection  means giving an
object its instance variables. [...].

Dependency injection is basically providing the objects that an
object needs (its dependencies) instead of having it construct them
itself. It`s a very useful technique for testing, since it allows
dependencies to be mocked or stubbed out.

 

Dependencies can be injected into objects by many means (such as
constructor injection or
setter injection). One can even use specialized dependency injection
frameworks (e.g Spring) to do that, but they certainly aren`t required.
You don`t need those frameworks to have dependency injection.
Instantiating and passing objects (dependencies) explicitly is just as
good an injection as injection by framework.

Dependency Injection (DI) is a technique to develop loosely coupled software
systems. Although this article won`t go into the details of DI as such, the
basic idea is this:

 

For example, consider a Car object.

 

A Car depends on wheels, engine, fuel, battery, etc. to
run. Traditionally we define the brand of such dependent objects along
with the definition of the Car object.

 

Without Dependency Injection (DI):

 

class Car{ 
private Wheel wh= new NepaliRubberWheel()
private Battery bt= new ExcideBattery()

//The rest
}

Here, the Car object is responsible for creating the dependent objects.

 

What if we want to change the type of its dependent object - say Wheel - after the initial NepaliRubberWheel() punctures?
We need to recreate the Car object with its new dependency say ChineseRubberWheel(), but only the Car manufacturer can do that.

 

When using dependency injection, objects are given their dependencies at run time rather than compile time (car manufacturing time).
So that we can now change the Wheel whenever we want. Here, the dependency (wheel) can be injected into Car at run time.

 

After using dependency injection:

 

class Car{ 
private Wheel wh= [Inject an Instance of Wheel at runtime]
private Battery bt= [Inject an Instance of Battery at runtime]
Car(Wheel wh,Battery bt) {
this.wh = wh
this.bt = bt
}
//Or we can have setters
void setWheel(Wheel wh) {
this.wh = wh
}
}

 

Filed Under: ASP DOT NET Computer Programming


facebook twitter facebook linkedin More +

Jimmy

 

Author Information

User Type: Tutor  Verified
Name: Jimmy
Uploaded Date: Jun 25,2016

About The Author

Comments