Yogi

SW Engg

Learn how to Implement Ninject in ASP.NET MVC in just 2 minutes

Ninject is a lightning-fast and ultra-lightweight Dependency Injector for .NET applications. By using it you can split your application into a collection of loosely-coupled, highly-cohesive pieces, and then glue them back together in a flexible manner. This makes your code easier to write, reuse, test, and modify.
In this tutorial you will learn to implement Ninject in ASP.NET MVC application in just 2 minutes time. Also note that the latest version of ASP.NET which is ASP.NET Core has an excellent Inbuilt Dependency Injection Feature which you can study more about it from this tutorial – Learn Dependency Injection in ASP.NET Core.
There are numerous tutorials on Ninject on the internet which are not only very lengthy but also quite difficult to understand. Reading such long tutorial takes a lot of a programmer’s time which he/she usually don’t have. I therefore decided to keep this tutorial very short and precise so that programmers can learn the use of Ninject in just 2 minutes time. So let’s start with it without delay.

Adding Ninject Package from NuGet

First you need to add Ninject in your ASP.NET MVC application, so in your Visual Studio, go to Package Manage Console window and add Ninject by using the following command:
PM> Install-Package Ninject -Version 3.3.4

Implement Ninject in ASP.NET MVC

Create the following Classes inside the Models folder of your project:
1. Weapon.cs
Add the following code to this class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace NinMVC.Models
{
    public interface IWeapon
    {
        string Strike();
    }

    public class Sword : IWeapon
    {
        public string Strike()
        {
           return "Samurai strikes with Sword";
        }
    }
}
There is an interface called
IWeapon 
that contains one member function called ‘
Strike()
’.
There is also a class called ‘Sword’ that implements this IWeapon
interface. The class provides the definition to the ‘
Strike()
’ member function of the interface and returns a string – ‘Samurai strikes with Sword’.
2. Samurai.cs
Add the following code to this class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace NinMVC.Models
{
    public class Samurai
    {
        public IWeapon Weapon;
        public Samurai(IWeapon weapon)
        {
            this.Weapon = weapon;
        }

        public string Strike()
        {
            string message = Weapon.Strike();
            return message;
        }
    }
}
This class constructor has a dependency for the
IWeapon
interface:
public IWeapon Weapon;
public Samurai(IWeapon weapon)
{
    this.Weapon = weapon;
}
The class also has the Member function called ‘
Strike()
’ and it invokes the ‘
Strike()
’ member function of the
IWeapon
interface.
string message = Weapon.Strike(); // need to resolve it
Now Ninject comes into place. I want Ninject to resolve the
dependency of IWeapon interface. I need it so that the ‘
Strike()
’ member of the Samurai.cs class can invoke the ‘Strike()’ member function of the Interface.
So to do it I create a new class and inherit it from
NinjectModule

(covered in the below section).
3. WarriorModule.cs
This class is inherited from NinjectModule (namespace
Ninject.Modules) and tells Ninject how to resolve the dependency for the
IWeapon
interface.
So add the following code to this class:
using Ninject.Modules;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace NinMVC.Models
{
    public class WarriorModule : NinjectModule
    {
        public override void Load()
        {
            this.Bind<IWeapon>().To<Sword>();
        }
    }
}
Look inside the
Load()
method where I tell Ninject how to provide
me an object of the Sword class whenever there is a dependency of
IWeapon
interface.
That’s all – ‘Now Ninject will automatically provide me the
object of Sword class whenever it sees the dependency of IWeapon interface’.
Note that the Ninject will provide the object of Sword class
based on the Transient scope. The transient scope is
default scope and can be specified as:
this.Bind<IWeapon>().To<Sword>().InTransientScope ();
There are 4 built in Scope which you can use in Ninject. These
are explained below:
  1. Transient - A new instance of the type will be created each
    time one is requested. This is the default scope if none is specified.
    Specified as
    .InTransientScope()
    .
  2. Singleton - Only a single instance of the type will be
    created, and the same instance will be returned for each subsequent request. Specified as
    .InSingletonScope()
    .
  3. Thread - One instance of the type will be created per thread.
    Specified as
    .InThreadScope()
    .
  4. Request - One instance of the type will be created for each Web
    Request. Specified as
    .InRequestScope()
    .

Controller code

Now it’s time to use the Samurai class in my Controller.
So add the following 2 namespaces in the controller:
using Ninject;
using NinMVC.Models;
Then inside any Action method you add the following 3 lines of code shown below:
var kernel = new StandardKernel(new WarriorModule());
var samurai = kernel.Get<Samurai>();

string message = samurai.Strike();
The first code line creates a Standard kernel whose job is to provide me the object of Samurai class using the
.Get()
method in the second code line.
The third code line is where I call the Strike() method of the Samurai class. The string variable called ‘message’ will get the value of – ‘Samurai strikes with Sword’.

Creating a small Ninject Application

Now I will update my Samurai so that he can use 3 types of weapons:
Swords
Arrows
Guns
I use the above logic to create a small Ninject application. Check the below video which shows how the attacks made by Samurai:
Go to the Weapon.cs class and add 2 new classes to it – ‘Arrow’ & ‘Gun’. The updated code is given below:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace NinMVC.Models
{
    public interface IWeapon
    {
        string Strike();
    }

    public class Sword : IWeapon
    {
        public string Strike()
        {
           return "Samurai strikes with Sword";
        }
    }

    public class Arrow : IWeapon
    {
        public string Strike()
        {
            return "Samurai strikes with Arrow";
        }
    }

    public class Gun : IWeapon
    {
        public string Strike()
        {
            return "Samurai strikes with Gun";
        }
    }
}
Next go to the WarriorModule.cs class and create bindings based on the value passed to it’s constructor.
The updated code is given below:
using Ninject.Modules;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace NinMVC.Models
{
    public class WarriorModule : NinjectModule
    {
        string Name;
        public WarriorModule(string name)
        {
            Name = name;
        }

        public override void Load()
        {
            if (Name == "Sword")
                this.Bind<IWeapon>().To<Sword>();
            else if (Name == "Arrow")
                this.Bind<IWeapon>().To<Arrow>();
            else if (Name == "Gun")
                this.Bind<IWeapon>().To<Gun>();
        }
    }
}

So now the dependency is resolved in 3 ways:
if (Name == "Sword")
    this.Bind<IWeapon>().To<Sword>();
else if (Name == "Arrow")
    this.Bind<IWeapon>().To<Arrow>();
else if (Name == "Gun")
    this.Bind<IWeapon>().To<Gun>();
Finally add 3 new Action methods to the controller:
public ActionResult Sword()
{
    var kernel = new StandardKernel(new WarriorModule("Sword"));
    var samurai = kernel.Get<Samurai>();

    string message = samurai.Strike();
    return View("Index", (object)message);
}

public ActionResult Arrow()
{
    var kernel = new StandardKernel(new WarriorModule("Arrow"));
    var samurai = kernel.Get<Samurai>();

    string message = samurai.Strike();
    return View("Index", (object)message);
}

public ActionResult Gun()
{
    var kernel = new StandardKernel(new WarriorModule("Gun"));
    var samurai = kernel.Get<Samurai>();

    string message = samurai.Strike();
    return View("Index", (object)message);
}
These action methods will tell Samurai to use a particular type of weapon to attack.
The Index View code is given below:
@model string

@{
    ViewBag.Title = "Home Page";
}

<h1>@Model</h1>

<h2>Go to the Following links</h2>

@Html.ActionLink("Sword", "Sword", "Home") <br />
@Html.ActionLink("Arrow", "Arrow", "Home") <br />
@Html.ActionLink("Gun", "Gun", "Home") <br/>
Now run your application and click the links and your Samurai will strike with a selected weapon only.
Conclusion
Ninject library is a great way to remove dependency injection. I hope you loved reading this tutorial, so please share this tutorial in facebook, twitter and linkedin.
❤ ❤ And when you’re ready to really dive into Web Development with ASP.NET Core, Check out the 
Introduction to ASP.NET Core MVC

Tags

More by Yogi

Topics of interest