Introduction To Dependency With Example Using NInject Container

Dependency Injection

If you want to describe these two words, you can simply say they “Inject the Dependency”. So what’s the dependency? If we talk about the object oriented world, class is dependent on any other class.

In MVC, it is more clear as the model fetches the data from DAL layer and presents  that data to the view. So we can say that model is dependent on the DAL.
dependent

So here  Dependency should be simply like constructor of class A.

Public A (B b) // Constructor of A

Dependency injection allows us to loosely couple classes in layered architecture, so implementing the DI the code is more and more maintainable.

So here we try to understand DI in the MVC way. The very basic flow of MVC request is like this,
flow
So here is where the problem begins.

Let's there is a controller and it consumes the Service from a class. In this way we can’t change the controller to consume different services easily and we need to provide “Mock” for unit testing,
controller
We always know that decoupling the two layers is always an interface. So here also Interface plays a vital part. So we are aware of our controller to IServices Interface rather than Services class. So implementing in this way you can change the implementation of services class at any point of time.

There are basically 3 ways of Implementing Dependency Injection,

  1. Constructor Injection
  2. Property Injection
  3. Method Injection

Here we will mainly talk about a more common way of dependency Injection – Constructor Injection,

  1. public class SampleTest : ISampleTest  
  2.     {  
  3.         public int AddNewSample(int i1, int i2)  
  4.         {  
  5.             return i1 + i2;  
  6.         }  
  7.     }  
  8. public interface ISampleTest  
  9.     {  
  10.         int AddNewSample(int i1, int i2);  
  11.     }  
  12. public class TestController : Controller  
  13.     {  
  14.         private ISampleTest _iSamleTest;  
  15.    
  16.         public TestController()  
  17.         {  
  18.    
  19.         }  
  20.         public TestController(ISampleTest iSamleTest)  
  21.         {  
  22.             _iSamleTest = iSamleTest;   
  23.         }  
  24.         // GET: Test  
  25.         public ActionResult Index()  
  26.         {  
  27.             int iCount = _iSamleTest.AddNewSample(2, 4);  
  28.             ViewBag.CountNumber = iCount;  
  29.             return View();  
  30.         }}  
Here the normal question in every mind is why dependency injection is useful. Here are basically three main points,

 

  1. Loosely coupled architecture
  2. Unit Testing – DI enables you to have complex dependencies with the mock dependency
  3. Validation – DI allows you to inject additional code between the dependencies. So the developer doesn't need to write code in every class.

Here I will show with an example. Create a sample mvc project here. Create 2 classes and both classes implement an interface.

interface

  1. public interface IShape  
  2.    {  
  3.        string GetshapeDetails();  
  4.    }  
  5.   
  6. public class RectangleShape : IShape  
  7.     {  
  8.    
  9.         public string GetshapeDetails()  
  10.         {  
  11.             return "Rectangle has 4 sides";  
  12.         }  
  13.     }  
  14.   
  15. public class TriangleShape : IShape  
  16.    {  
  17.        public string GetshapeDetails()  
  18.        {  
  19.            return "Triangle has 3 sides";  
  20.        }  
  21.    }  
And in main controller we will write code like this.
  1. public class HomeController : Controller  
  2.   {  
  3.       private IShape _iShape;  
  4.    
  5.       public HomeController(IShape iShape)  
  6.       {  
  7.           _iShape = iShape;  
  8.       }  
  9.       public ActionResult Index()  
  10.       {  
  11.           string shapedetails = _iShape.GetshapeDetails();  
  12.           ViewBag.Message = shapedetails;  
  13.           return View(shapedetails as object);  
  14.       }  
  15.   }  
When we run this code, we will get the following error,

error

Now we will add the container NInject,

NInject

By adding this nuget package, we will get NInject Webcommon file in app_start,

app_start

We will write this code in NInject Webcommon
  1. /// <summary>  
  2.        /// Load your modules or register your services here!  
  3.        /// </summary>  
  4.        /// <param name="kernel">The kernel.</param>  
  5.        private static void RegisterServices(IKernel kernel)  
  6.        {  
  7.            kernel.Bind<IShape>().To<RectangleShape>();  
  8.        }    
If we run and compile the code, we will see that the Rectangle class GetshapeDetails will be called. And if we change it the code will look like this.
  1. private static void RegisterServices(IKernel kernel)  
  2.        {  
  3.            kernel.Bind<IShape>().To<TriangleShape>();  
  4.        }   
The TriangleShape shape details method will be called.

 

Up Next
    Ebook Download
    View all
    Learn
    View all