Tuesday, January 21, 2014

Dependency Injection example

(I am trying to learn DI. Below is an Example from Adam Freeman's book - Pro ASP.Net MVC 5. Below is my attempt at understading the example in the book)
Dependency Injection example with Ninject: 

Starting point 

1. ShoppingCart's constructor expects a concrete class's object (i.e. object of class LinqValueCalculator)
2. HomeController's Index action is instantiating 2 objects before using them (observe the 'new' keyword being used in 2 lines of code)


Summary

In Stage1, we 'fix' ShoppingCart class (by transferring the responsibility of creating the object to HomeController class). 
Putting this in another way - we make it easier to write the ShoppingCart class, by asking HomeController to pass, as parameter to constructor, whatever ShoppingCart class needs 
Now we have to 'fix' HomeController class 

In Stage 2, we fix HomeController class

Stage 1 - left page in below screenshot

In page 124 (left page in below screenshot):

ShoppingCart has been 'fixed' now:
-- it has 'declared' that it has a dependency on an object of type IValueCalculator
-- It has done this 'declaration' via its constructor
-- basically it is saying - send me the object and I will use it; i am not going to go through the trouble of creating it
-- Also notice that, in ShoppingCart's constructor, concrete class LinqValueCalculator has been replaced by an interface IValueCalculator

- So, now the responsibility of getting hold of a IValueCalculator object has been transferred to Index() method of HomeControler.cs

Stage 2 - right page in below screenshot

In page 128 (right page in below screenshot):

Now, we use the same strategy with HomeController.cs :
-- we make it 'declare' that it has a dependency on an IValueCalculator object via its constructor
-- basically, now, it is also saying - send me the object and I will use it; i am not going to go through the trouble of creating it)

- So the question is - who is going to create the object now (since each class seems to be handing over that responsibility to someone else, and there is no one else to hand that responsibility over to) ?
Ninject or such DI container will do that...


No comments:

Post a Comment

Followers

Blog Archive