How to Use Ninject Framework with MVC

Most people think that IOC containers are for large applications only. They are wrong, as they can be used in any size application; i.e, from small to large, because this will make your application maintainable and improve the quality of your application.

Some people have another question in mind, which is: How much does it cost to get IOC Containers?

Oh, most IOC containers are free to download and use.

In this, Ninject is completely free to use for personal and commercial projects.

You can check here for more information.

ninject

What is Ninject framework?

The Ninject framework is an ultra-lightweight framework from Ninject, which will help us to resolve dependency.

What is Dependency injection?

Dependency injection is a design pattern, which is used to remove hard code dependency.

Types of Injection

  • Constructor Injection
  • Property Setter Injection (Properties)
  • Method Injection

If you have a look at the internet, you will find most people show an example of Constructor Injection. In this article, I will show you how to use all the three types of injectios.

Tools Required for Demo,

  • Visual Studio 2012
  • SQL Server 2008
Let’s start with creating an MVC project, using a basic project template.

Creating Application

Open Visual Studio IDE on the start page. Select new project.

visual studio IDE
Figure 1. Start page

After selecting new project link, a new project dialog will appear. Inside it, select templates - Visual C# needs to be selected inside this. Select Web, after which you will see the various project templates (Webforms , MVC , Asp.net AJAX Server control). In this, select “ASP.NET MVC 4 Web Application. ” After selecting, just name your project as “MvcNInject” and finally click the OK button to create the project.

Selecting Templates

Selecting Template
Figure 2. Selecting Template

After clicking OK button, another project template selection wizard will pop up with the name “New ASP.NET MVC 4 Project.” In this template, select basic template, set view engine as Razor and we are not going to create unit testing for this project. Hence, do not check this option and finally click OK button and it's done.

MVC 4 Project
Figure 3. Selecting MVC 4 Project

After selecting all the options, as told above, click OK button and your project will be created.

Project structure after creating MvcNInject project

Project structure
Figure 4. Project structure

After creating our project, we are going to add class Library to the project, so that it feels like a real application when we create it.

Adding [Class library] to Web project

We are going to Add three [Class libraries].
  1. MvcNInject.Model
  2. MvcNInject.Interface
  3. MvcNInject.Concrete

MvcNInject.Model [Class library] will contain all the models.
MvcNInject.Interface [Class library] will contain all the interfaces.
MvcNInject.Concrete [Class library] will contain all the concrete classes.


Let’s start doing it.

Adding MvcNInject.Model [Class library]

First, we are going to add Model layer with the name MvcNInject.Model Layer.

Tips

You might think since we have Model folder in the project, then why are we adding MvcNInject.Model layer? It is because if we have a large project, it is better to move Model into [Class library] and add reference to the main project.

To add [Class library], just right click on your project from the list and select Add, followed by selecting the new project.

add
Figure 5. Steps to add Class library

After selecting the new project, a new dialog will pop up with the name Add New Project. As shown below, select the type Visual C# inside it. Select Windows and from the template, select [Class Library] and then name your project as MvcNInject.Model and click OK button.

MvcNInject.Model
Figure 6. Adding MvcNInject.Model [Class library]

Project structure after Adding MvcNInject.Model

structure

Now we are going to Add Interface to make your application's loose couple.

Adding MvcNInject.Interface [Class library]

We are going to add MvcNInject.Interface in a similar way as we have added MvcNInject.Model [Class library].

To add [Class library] just right click on your project from List and select Add - then select New Project.

After selecting a new project, a new dialog will pop up with the name Add new Project from the panel and select type Visual C#. Inside it, select Windows. From the template, select [Class Library] and then name your project as MvcNInject.Interface and click OK button.

MvcNInject.Interface
Figure 7. Adding MvcNInject.Interface [Class library]

Project structure after Adding MvcNInject.Interface

structure

Now, we are going to add concrete classes, which will implement an interface.

Adding MvcNInject.Concrete [Class library]

We are going to add MvcNInject.Concrete in a similar way as we have added MvcNInject.Interface [Class library].

To add [Class library], just right click on your project from the list, select Add followed by selecting the New Project.

After selecting New Project, a new dialog will pop up with the name Add new Project from the panel. Select type Visual C#; inside it, select Windows from the template, select [Class Library], name your project as MvcNInject.Concrete and click OK button.

MvcNInject
Figure 8. Adding MvcNInject.Concrete [Class library]

Project structure after Adding MvcNInject.Concrete

structure

Now, we have completed adding all [Class library] in the project.

Adding Model in MvcNInject.Model

Next, we are going add a model in [MvcNInject.Model] with the name Event.

For adding model, just right click on MvcNInject.Model, and select Add, followed by selecting the class inside it.

After clicking on the class, add new item and a  dialog will pop up with the class. Select and it will ask for the class name. Here, we are going to enter the class name as an “Event”.

Model

After adding the model, let’s add some properties to it.

Adding Properties to EventModel

  1. using System;    
  2. using System.Collections.Generic;    
  3. using System.ComponentModel.DataAnnotations;    
  4. using System.Linq;    
  5. using System.Text;    
  6. using System.Threading.Tasks;    
  7.     
  8. namespace MvcNInject.Model    
  9. {    
  10.     public class EventModel    
  11.     {    
  12.         [Key]    
  13.         public int EventID { getset; }    
  14.         public string EventName { getset; }    
  15.         public string EventStarts { getset; }    
  16.         public string EventEnds { getset; }    
  17.         public string EventLocation { getset; }    
  18.     }    
  19.  
After adding the model and properties, now let’s add an interface.

Adding Interface in MvcNInject.Interface

We are going add an interface in MvcNInject.Interface.

To ad an interface, just right click on MvcNInject.Interface followed by selecting add. Inside it, select Add New Item menu.

After clicking Add New item, a new Add New item dialog will pop up. Inside it, select an interface and then we are going to name an interface as an “IEvent”.

Adding Interfaces
Figure 9. Adding Interface in MvcNInject.Interface

MvcNInject.Interface

After adding an interface, we are going to add the reference of MvcNInject.Model in MvcNInject.Interface to access the model inside an interface.

Adding Reference of MVCNInject.Model (Event) in MVCNInject.Interface (IEvent)

To add a reference, just right click on MvcNInject.Interface [Class Library], followed by selecting add reference. After selecting, a new dialog will pop up with the name Reference Manager. Inside it, select MvcNInject.Model and click OK button.

reference

reference
Figure 10. Adding reference of MvcNInject.Model to MvcNInject.Interface

After adding reference now, we are going to declare some method in an interface.

Declaring method in MvcNInject.Interface 
  1. using MvcNInject.Model;    
  2. using System;    
  3. using System.Collections.Generic;    
  4. using System.Linq;    
  5. using System.Text;    
  6. using System.Threading.Tasks;    
  7.     
  8. namespace MvcNInject.Interface    
  9. {    
  10.     public interface IEvent    
  11.     {    
  12.         void Add(EventModel _Event);     // Create New Event    
  13.         void Update(EventModel _Event);  // Modify Event    
  14.         void Delete(EventModel _Event);  // Delete Event    
  15.         EventModel GetById(int id); // Get an Single Event details by id    
  16.         IEnumerable<EventModel> GetAll();  // Gets All Event details    
  17.     }    
  18. }  
After declaring all the methods in an interface, let’s add concrete class in MvcNInject.Concrete.

Adding Class in MVCNInject.Concrete

We are going to add class in MvcNInject.Concrete in [Class library] in the project.

To add the model, just right click on MvcNInject.Concrete. Select Add - inside that Select Class.

After Clicking on class, add new item and a dialog will pop up with class select and ask for class name; here we are going to enter class name as “EventConcrete”.

EventConcrete

Adding Reference of MvcNInject.Interface (Event) in MvcNInject.Concrete (IEvent)

To Add Reference just right Click on MvcNInject.Concrete [Class Library] then select Add Reference; after selecting a new dialog will pop up with the name Reference Manager; inside that select MvcNInject.Interface and MvcNInject.Model. Both are required, then click on OK button.

Reference
Figure 11. Adding reference of MvcNInject.Interface and MvcNInject.Model to MvcNInject.Concrete

Now we have finished adding Reference, now let’s implement all methods declared in IEvent Interface in EventConcrete class.

EventConcrete class will implement IEvent interface
  1. using MvcNInject.Interface;    
  2. using System;    
  3. using System.Collections.Generic;    
  4. using System.Linq;    
  5. using System.Text;    
  6. using System.Threading.Tasks;    
  7.     
  8. namespace MvcNInject.Concrete    
  9. {    
  10.     public class EventConcrete : IEvent    
  11.     {    
  12.     
  13.     }    
  14. }  
Now after implementing IEvent interface next we are going perform CRUD operation using Dapper ORM.

Adding Dapper ORM to MvcNInject.Concrete [Class Library]


Now to perform all database operations such as CRUD I am going to use Dapper ORM.

We are going add Reference of Dapper ORM from NuGet package manager and we are going add it in MvcNInject.Concrete [Class Library].

To open Manage NuGet Package dialog just right click on MvcNInject.Concrete [Class Library] and from the list select Manage NuGet package.

Snapshot of Manage NuGet package dialog.

In search box enter Dapper. And select Dapper dot net as show below and click on Install button.

DapperORM
Figure 12. Adding DapperORM from NuGet

Project structure after Adding Dapper

structure

After adding Dapper ORM next we Create Database and Table and Store procedure for performing CRUD operation.

Database Part

Here I am going to show the database part.

I have created a Database with the name [EventDB].

Database

After that I have created a table inside EventDB database with name [EventTB].

Table structure
Figure 13. Table structure

We are going use stored procedure for performing CRUD operation.

Below are the names of the stored procedure which I have created. I have provided this stored procedure to download.
store procedure

Connection string used
  1. <connectionStrings>  
  2.    <add name="DefaultConnection"  
  3.    providerName="System.Data.SqlClient"  
  4.    connectionString="Data Source=sai-pc;Database=EventDB;UID=sa;Password=Pass$123" />  
  5. </connectionStrings>  
After Completing the Database part we are again going back to EventConcrete class in MvcNInject.Concrete [Class Library].

EventConcrete class will implement IEvent interface

In this part I am implementing all methods which are declared in interface and using Dapper to perform Crud operation.
  1. using Dapper;    
  2. using MvcNInject.Interface;    
  3. using MvcNInject.Model;    
  4. using System;    
  5. using System.Collections.Generic;    
  6. using System.Configuration;    
  7. using System.Data;    
  8. using System.Data.SqlClient;    
  9. using System.Linq;    
  10. using System.Text;    
  11. using System.Threading.Tasks;    
  12.     
  13. namespace MvcNInject.Concrete    
  14. {    
  15.     public class EventConcrete : IEvent    
  16.     {    
  17.         public void Add(EventModel Event)    
  18.         {    
  19.             using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString))    
  20.             {    
  21.                 con.Open();    
  22.                 SqlTransaction sqltans = con.BeginTransaction();    
  23.                 var param = new DynamicParameters();    
  24.                 param.Add("@EventID", Event.EventID);    
  25.                 param.Add("@EventName", Event.EventName);    
  26.                 param.Add("@EventStarts", Event.EventStarts);    
  27.                 param.Add("@EventEnds", Event.EventEnds);    
  28.                 param.Add("@EventLocation", Event.EventLocation);    
  29.                 var result = con.Execute("sprocEventTBInsertUpdateSingleItem",    
  30.                       param,    
  31.                       sqltans,    
  32.                       0,    
  33.                       commandType: CommandType.StoredProcedure);    
  34.     
  35.                 if (result > 0)    
  36.                 {    
  37.                     sqltans.Commit();    
  38.                 }    
  39.                 else    
  40.                 {    
  41.                     sqltans.Rollback();    
  42.                 }    
  43.     
  44.             }    
  45.     
  46.         }    
  47.     
  48.         public void Update(EventModel Event)    
  49.         {    
  50.             using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString))    
  51.             {    
  52.                 con.Open();    
  53.                 SqlTransaction sqltans = con.BeginTransaction();    
  54.                 var param = new DynamicParameters();    
  55.                 param.Add("@EventID", Event.EventID);    
  56.                 param.Add("@EventName", Event.EventName);    
  57.                 param.Add("@EventStarts", Event.EventStarts);    
  58.                 param.Add("@EventEnds", Event.EventEnds);    
  59.                 param.Add("@EventLocation", Event.EventLocation);    
  60.                 var result = con.Execute("sprocEventTBInsertUpdateSingleItem",    
  61.                     param,    
  62.                     sqltans,    
  63.                     0,    
  64.                     commandType: CommandType.StoredProcedure);    
  65.     
  66.     
  67.                 if (result > 0)    
  68.                 {    
  69.                     sqltans.Commit();    
  70.                 }    
  71.                 else    
  72.                 {    
  73.                     sqltans.Rollback();    
  74.                 }    
  75.             }    
  76.         }    
  77.     
  78.         public void Delete(EventModel Event)    
  79.         {    
  80.             using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString))    
  81.             {    
  82.                 con.Open();    
  83.                 SqlTransaction sqltans = con.BeginTransaction();    
  84.                 var param = new DynamicParameters();    
  85.                 param.Add("@EventID", Event.EventID);    
  86.                 var result = con.Execute("sprocEventTBDeleteSingleItem",    
  87.                     param,    
  88.                     sqltans,    
  89.                     0,    
  90.                     commandType: CommandType.StoredProcedure);    
  91.     
  92.                 if (result > 0)    
  93.                 {    
  94.                     sqltans.Commit();    
  95.                 }    
  96.                 else    
  97.                 {    
  98.                     sqltans.Rollback();    
  99.                 }    
  100.             }    
  101.         }    
  102.     
  103.         public EventModel GetById(int id)    
  104.         {    
  105.             using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString))    
  106.             {    
  107.                 con.Open();    
  108.                 var param = new DynamicParameters();    
  109.                 param.Add("@EventID", id);    
  110.                 return con.Query<EventModel>("sprocEventTBSelectSingleItem",    
  111.                     param,    
  112.                     null,    
  113.                     true,    
  114.                     0,    
  115.                     commandType: CommandType.StoredProcedure).SingleOrDefault();    
  116.             }    
  117.         }    
  118.     
  119.         public IEnumerable<EventModel> GetAll()    
  120.         {    
  121.     
  122.             using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString))    
  123.             {    
  124.                 con.Open();    
  125.                 var param = new DynamicParameters();    
  126.                 return con.Query<EventModel>("sprocEventTBSelectList",    
  127.                     null,    
  128.                     null,    
  129.                     true,    
  130.                     0,    
  131.                     commandType: CommandType.StoredProcedure).ToList();    
  132.             }    
  133.         }    
  134.     
  135.     
  136.     
  137.     }    
  138. }  
After completing the implementation next we are going to add reference of Model and Interface in Main web Project [MvcNInject].

Adding Reference of Model and Interface to Main Web Project MvcNInject

To Add Reference just right Click on MvcNInject then select Add Reference; after selecting a new dialog will pop up with the name Reference Manager, inside that select MvcNInject.Interface , MvcNInject.Model , MvcNInject.Concrete which are required then click on OK button.

reference
Figure 14. Adding reference of all three class libraries to main Web Project (MvcNInject)

Reference after adding in Project

After adding this reference now let’s Add a Controller with the name EventController

Adding Controller

For adding Controller Just Right click on Controller Folder, inside that select Add, and then select Controller.

After clicking on Controller a new dialog will pop up with the name Add Controller.

I will name Controller “EventController” and in Template I will choose “MVC controller with empty read/write actions” and finally click on the Add button.

Event Controller
Figure 15. Adding Event Controller

Project Structure after Adding EventController

Structure

EventController with all Empty Action Method

Method
Figure 15. All Action Method of Event Controller

After adding Controller now we are going to add reference of Ninject Framework to MvcNInject Application.

Adding Ninject Framework Reference

Ninject

There are two ways of Installing Microsoft Unity Framework,

Installing Using Manage NuGet package

To open Manage NuGet Package dialog just right click on MvcNInject and from List select Manage NuGet package.

In search box enter Ninject MVC4.

And select Ninject.MVC4 as show below and click on Install button and it will get installed.

Ninject framework
Figure 16. Installing Ninject framework

Installing Using Package Manager Console

To install Ninject Framework using Package Manager Console, first from IDE menu select Tools - then NuGet package Manager - inside that select Package Manager Console.

In Package Manager Console enter Command: Install-Package Ninject.MVC4

Install-Package Ninject.MVC4

After entering command just press enter button it will get Installed.

console

After Installing Ninject Framework you should be able to see one class, NinjectWebCommon class, in the Application start folder [App_Start].

Project Structure after Adding Ninject Framework

Structure

Below you can see a snapshot of NinjectWebCommon classes.

class
Figure 17. NinjectWebCommon class preview

After that we are going to add class with name NinjectResolver which will store all Mapping of Registered Types in it.

A NinjectResolver will inherit System.Web.Mvc.IDependencyResolver,

  1. using Ninject;    
  2. using System;    
  3. using System.Collections.Generic;    
  4. using System.Linq;    
  5. using System.Web;    
  6.     
  7. namespace MvcNInject.App_Start    
  8. {    
  9.     public class NinjectResolver: System.Web.Mvc.IDependencyResolver    
  10.     {    
  11.         private readonly IKernel _kernel;    
  12.     
  13.         public NinjectResolver()    
  14.         {    
  15.             _kernel = new StandardKernel();    
  16.             AddBindings();    
  17.         }    
  18.         public object GetService(Type serviceType)    
  19.         {    
  20.             return _kernel.TryGet(serviceType);    
  21.         }    
  22.         public IEnumerable<object> GetServices(Type serviceType)    
  23.         {    
  24.             return _kernel.GetAll(serviceType);    
  25.         }    
  26.         private void AddBindings()    
  27.         {    
  28.            // _kernel.Bind<To, From>(); // Registering Types    
  29.         }    
  30.     }    
  31.         
  32. }  
Registering Types in Ninject

Now we are going registers all the type mappings with the Ninject container.

Ninject
Figure 18. Ninject

Now we are going to register types in NinjectResolver classes;  we have a method with name AddBindings() in which we are going to register.
  1. private void AddBindings()  
  2. {  
  3.    this._kernel.Bind<IEvent>().To<EventConcrete>(); // Registering Types  
  4. }  
This indicates that whereever we are using IEvent for constructor injection it should inject EventConcrete object there.

In this method you can register all your mapping of your application.

Now we are required to create object; all object creation will be handled by Ninject container; which is to say you ask the Ninject container to do it for you so that the container can resolve any dependencies.

Here is complete NinjectResolver Class View.

NinjectResolver Class
  1. using MvcNInject.Concrete;    
  2. using MvcNInject.Interface;    
  3. using Ninject;    
  4. using System;    
  5. using System.Collections.Generic;    
  6. using System.Linq;    
  7. using System.Web;    
  8.     
  9. namespace MvcNInject.App_Start    
  10. {    
  11.     public class NinjectResolver: System.Web.Mvc.IDependencyResolver    
  12.     {    
  13.         private readonly IKernel _kernel;    
  14.     
  15.         public NinjectResolver()    
  16.         {    
  17.             _kernel = new StandardKernel();    
  18.             AddBindings();    
  19.         }    
  20.     
  21.         public object GetService(Type serviceType)    
  22.         {    
  23.             return _kernel.TryGet(serviceType);    
  24.         }    
  25.     
  26.         public IEnumerable<object> GetServices(Type serviceType)    
  27.         {    
  28.             return _kernel.GetAll(serviceType);    
  29.         }    
  30.     
  31.         private void AddBindings()    
  32.         {    
  33.             this._kernel.Bind<IEvent>().To<EventConcrete>(); // Registering Types    
  34.         }    
  35.     }    
  36.         
  37. }  
Now one final step is remaining, we have just registered Types in NinjectResolver class and we need to call this class in Global.asax Application_Start() Method.

In Application_Start() method we are going to call our NinjectResolver class.
  1. DependencyResolver.SetResolver(new NinjectResolver());  
Below you can see the complete Global.asax Class.

NinjectResolver Class
  1. using MvcNInject.App_Start;    
  2. using System;    
  3. using System.Collections.Generic;    
  4. using System.Linq;    
  5. using System.Web;    
  6. using System.Web.Http;    
  7. using System.Web.Mvc;    
  8. using System.Web.Optimization;    
  9. using System.Web.Routing;    
  10.     
  11. namespace MvcNInject    
  12. {    
  13.     public class MvcApplication : System.Web.HttpApplication    
  14.     {    
  15.         protected void Application_Start()    
  16.         {    
  17.             AreaRegistration.RegisterAllAreas();    
  18.     
  19.             DependencyResolver.SetResolver(new NinjectResolver());// Calling  NinjectResolver Class    
  20.     
  21.             WebApiConfig.Register(GlobalConfiguration.Configuration);    
  22.             FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);    
  23.             RouteConfig.RegisterRoutes(RouteTable.Routes);    
  24.             BundleConfig.RegisterBundles(BundleTable.Bundles);    
  25.         }    
  26.     }    
  27. }  
After completing with calling class in Global.asax now we are going to move forward to EventController and in this controller we are going to implement Constructor Injection.
  1. public class EventController : Controller    
  2. {    
  3.      private readonly IEvent _IEvent;    
  4.      
  5.      public EventController(IEvent IEvent)    
  6.      {    
  7.          _IEvent = IEvent;    
  8.      }    
  9. }   
Below is the code snippet of EventController.
  1. using MvcNInject.Interface;    
  2. using MvcNInject.Model;    
  3. using System;    
  4. using System.Collections.Generic;    
  5. using System.Linq;    
  6. using System.Web;    
  7. using System.Web.Mvc;    
  8. namespace MvcNInject.Controllers    
  9. {    
  10.     public class EventController : Controller    
  11.     {    
  12.         private readonly IEvent _IEvent;    
  13.         
  14.         public EventController(IEvent IEvent)    
  15.         {    
  16.             _IEvent = IEvent;    
  17.         }    
  18.     
  19.             
  20.         public ActionResult Index()    
  21.         {    
  22.             var Data = _IEvent.GetAll();    
  23.             return View(Data);    
  24.         }    
  25.         //    
  26.         // GET: /Event/Details/5    
  27.     
  28.         public ActionResult Details(int id)    
  29.         {    
  30.             var Data = _IEvent.GetById(id);    
  31.             return View(Data);    
  32.         }    
  33.         //    
  34.         // GET: /Event/Create    
  35.     
  36.         public ActionResult Create()    
  37.         {    
  38.             return View();    
  39.         }    
  40.         //    
  41.         // POST: /Event/Create    
  42.     
  43.         [HttpPost]    
  44.         public ActionResult Create(EventModel EventModel)    
  45.         {    
  46.             try    
  47.             {    
  48.                 _IEvent.Add(EventModel);    
  49.                 return RedirectToAction("Index");    
  50.             }    
  51.             catch    
  52.             {    
  53.                 return View();    
  54.             }    
  55.         }    
  56.         //    
  57.         // GET: /Event/Edit/5    
  58.     
  59.         public ActionResult Edit(int id)    
  60.         {    
  61.             var Editdata = _IEvent.GetById(id);    
  62.             return View(Editdata);    
  63.         }    
  64.         //    
  65.         // POST: /Event/Edit/5    
  66.     
  67.         [HttpPost]    
  68.         public ActionResult Edit(EventModel EventModel)    
  69.         {    
  70.             try    
  71.             {    
  72.                 _IEvent.Update(EventModel);    
  73.                 return RedirectToAction("Index");    
  74.             }    
  75.             catch    
  76.             {    
  77.                 return View();    
  78.             }    
  79.         }    
  80.         //    
  81.         // GET: /Event/Delete/5    
  82.         public ActionResult Delete(int id)    
  83.         {    
  84.             var Deletedata = _IEvent.GetById(id);    
  85.             return View(Deletedata);    
  86.         }    
  87.         //    
  88.         // POST: /Event/Delete/5    
  89.         [HttpPost]    
  90.         public ActionResult Delete(EventModel EventModel)    
  91.         {    
  92.             try    
  93.             {    
  94.                 _IEvent.Delete(EventModel);    
  95.                 return RedirectToAction("Index");    
  96.             }    
  97.             catch    
  98.             {    
  99.                 return View();    
  100.             }    
  101.         }    
  102.     }    
  103. }  
After completing the accessing of all Method of EventConcrete Class within all Action Method Using NInject constructor injection, now we are going to add all View of all Action Method one by one.

Adding View (Create / Update / Delete / Index)

For Adding View just right click inside Index ActionResult Method and Select "Add View" to create the view template for our Index form.

Add View
Figure 19. Adding Views of all Action Method.

Here in the below snapshot I have selected View engine as Razor and we are going to create a strongly typed view, for that I have selected Model class EventModel and we want to create an input form, for that I have selected Create in Scaffold template, finally click on Add button.

Add View
Figure 20. Steps for Adding View

After clicking on Add button the View will get created and it is stored in the Views folder; inside this folder, there I created a folder with the same name as Controller [Event]; inside that this View will be placed.

In a similar way we are going to Add View for all Action Methods.

Adding Details View

For Adding Details View we are just going to follow a similar step --  in Model we are going to select Event and in Scaffold template we are going to select Details.

Adding Create View

For Adding Create View we are just going to follow a similar step --  in Model we are going to select Event and in Scaffold template we are going to select Create.

Adding Edit View

For Adding Edit View we are just going to follow a similar step --  in Model we are going to select Event and in Scaffold template we are going to select Edit.

Adding Delete View

For Adding Delete View we are just going to follow a similar step --  in Model we are going to select Event and in Scaffold template we are going to select Delete.

After completing adding all View,  your Views Folder should look like this as show below.

Project structure after Adding Views

structure

Now we have completed adding Views, let’s run the application.

Run Application

To access the application we are going to enter URL: http://localhost:#####/ Event/Create

(##### is local host port number).

After running application we are going to see how constructor injection takes place.

By attaching debugger at constructor you can check what is getting injected.

Debugging Preview of EventController while Constructor is injecting

Constructor
Figure 21. Debugging Preview of Event Controller while Constructor is injecting

Event

After having a look on the debugging process we have called Create Action method and it will return a View [Create].

Create View

View
Figure 22. Accessing Create View for inserting data

So far we have done constructor injection.

Now let’s have a look at Property Setter Injection.

Property Injection

Here I have created Property with name [_Event];  to inject in property we need to Use [Inject] attribute on top of the Property where you want it.

See below example.
  1. [Inject]  
  2. public IEvent _Event { setget; }  
Debugging Preview of EventController while Using Property injecting

If you have looked closely then you can see I have commented Constructor; and still we are able to inject using Property injection.

Property Injection
Figure 23. Property Injection

Method Injection

Here I have created Method Injection. To use this just create a Method with any unique name, I have named it DemoMethod and this method should take the Interface as Parameter, after that, on that method, just add [Inject] Attribute.
  1. [Inject]  
  2. public void DemoMethod(IEvent IEvent)  
  3. {  
  4.    _IEvent = IEvent;  
  5. }  
Method Injection
Figure 24. Method Injection

After entering data I am going to click on Create button to save data in the database.

Let’s check your table --  EventTB has data inserted in it. Yes, it is there.

Result after Creating Event [Sql server]

Sql Query
Figure 25. Sql Query

In a similar way we can access all views which we have created.

If you have looked closely the object creation process is moved out;  we are no longer creating the object manually.

Finally we have come a long way and step by step learned how to use NInject with MVC.

Download source code from here.


Similar Articles