Dependency Injection Using Ninject

In my first article, I explained about Design Pattern and how to implement Dependency Injection using Microsoft Unity.
Before going inside this article I would like you to go through the following link, where you will get the basic idea about design pattern and Dependency Injection.
Let me explain once again what Dependency Injection is.

Dependency injection is a technique to develop an application in an independent way. Independent in the sense that every module of the application should be unique and will not depend upon other modules. They should be loosely coupled.

Let me discuss here what Tightly Coupled and Loosely Coupled means in software development.  

Tight Coupling

It means two classes or two modules are fully dependent upon each other. And changing one class object may lead to change in several areas in other class. When we are creating an object of a class and calling that class method by its object from another class, then we will say that the two classes are tightly coupled or dependent on each other.

Loose Coupling

It means two objects are independent and an object can use another object without being dependent on it. They are unique. In software development we always prefers Loosely coupling application.

Here we will see how to implement Dependency injection using Ninject.

Ninject:

 

Ninject is a lightning-fast, ultra-lightweight dependency injector for .NET applications. It helps you split your application into a collection of loosely-coupled, highly-cohesive pieces, and then glue them back together in a flexible manner. By using Ninject to support your software architecture, your code will become easier to write, reuse, test, and modify. To learn more about Ninject you can visit CodePlex from here

Step 1: Create an ASP.NET Web Application.

 

Step 2:
Select MVC template.

 

Step 3: Add one class Employee.cs and an interface IEmployee.cs in the project as shown in the Solution Explorer.

 

Step 4: Go To Manage Nuget Package and search for Ninject.Mvc3. 

 

Step 5: After installing this Ninject we found these 3 assemblies in our References.

 

Now if we check the App_start folder we will find NinjectWebCommon.cs class.

 

Step 6: Go to your Iemployee interface and add the following abstract method. 
  1. public interface Iemployee  
  2. {  
  3.     string SaveData();  
  4.          
  5. }  
Step 7: Go to your Employee Class and implement the abstract class method as follows, to show a simple message. 
  1. public class Employee:Iemployee  
  2. {  
  3.     public string SaveData()  
  4.     {  
  5.         return "Data Saved....";  
  6.              
  7.     }  
  8. }  
Step 8: Go to the Ninjectwebcommon.cs class in App_Start and register the employee class and Iemployee interface there. 
  1. [assembly: WebActivatorEx.PreApplicationStartMethod(typeof(DependencyInjection.App_Start.NinjectWebCommon), "Start")]  
  2. [assembly: WebActivatorEx.ApplicationShutdownMethodAttribute(typeof(DependencyInjection.App_Start.NinjectWebCommon), "Stop")]  
  3.   
  4. namespace DependencyInjection.App_Start  
  5. {  
  6.     using System;  
  7.     using System.Web;  
  8.   
  9.     using Microsoft.Web.Infrastructure.DynamicModuleHelper;  
  10.   
  11.     using Ninject;  
  12.     using Ninject.Web.Common;  
  13.   
  14.     public static class NinjectWebCommon   
  15.     {  
  16.         private static readonly Bootstrapper bootstrapper = new Bootstrapper();  
  17.   
  18.         /// <summary>  
  19.         /// Starts the application  
  20.         /// </summary>  
  21.         public static void Start()   
  22.         {  
  23.             DynamicModuleUtility.RegisterModule(typeof(OnePerRequestHttpModule));  
  24.             DynamicModuleUtility.RegisterModule(typeof(NinjectHttpModule));  
  25.             bootstrapper.Initialize(CreateKernel);  
  26.         }  
  27.           
  28.         /// <summary>  
  29.         /// Stops the application.  
  30.         /// </summary>  
  31.         public static void Stop()  
  32.         {  
  33.             bootstrapper.ShutDown();  
  34.         }  
  35.           
  36.         /// <summary>  
  37.         /// Creates the kernel that will manage your application.  
  38.         /// </summary>  
  39.         /// <returns>The created kernel.</returns>  
  40.         private static IKernel CreateKernel()  
  41.         {  
  42.             var kernel = new StandardKernel();  
  43.             try  
  44.             {  
  45.                 kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);  
  46.                 kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();  
  47.   
  48.                 RegisterServices(kernel);  
  49.                 return kernel;  
  50.             }  
  51.             catch  
  52.             {  
  53.                 kernel.Dispose();  
  54.                 throw;  
  55.             }  
  56.         }  
  57.   
  58.         /// <summary>  
  59.         /// Load your modules or register your services here!  
  60.         /// </summary>  
  61.         /// <param name="kernel">The kernel.</param>  
  62.         private static void RegisterServices(IKernel kernel)  
  63.         {  
  64.             kernel.Bind<Iemployee>().To<DependencyInjection.Employee>().InRequestScope();  
  65.               
  66.         }          
  67.     }  
  68. }   
Now almost all the work has been finished. Now we will see how to decouple these things.
 
Note: When we are creating an object of a class and calling that class method by its object from another class, then we will say that the two classes are tightly coupled or dependent on each other.

So our aim here is to decouple each class, so here without creating any instance, I will call another class method. Let's see how.
 
Step 9: In the Home Controller create a constructor and just add the following code: 
  1. public class HomeController : Controller  
  2. {  
  3.     Iemployee iemployee;  
  4.     public HomeController(Iemployee _iemployee)  
  5.     {  
  6.         iemployee = _iemployee;  

  7.     }  
  8. }
So, here I am doing a Constructor Injection by creating a constructor and passing the dependency in the constructor.

Now when you try to access the employee class method you can do as follows in another action method.

 

Here is the code of the screenshot.
  1. public ActionResult Index()  
  2. {  
  3.     string result = iemployee.SaveData();  
  4.     return Content(result);  
  5. }  
Now just save the program and run. It will produce the following output:

run
So in this we saw how to implement dependency injection using Ninject.
 
Read more articles on Design Pattern:

Up Next
    Ebook Download
    View all
    Learn
    View all