You've seen this! Your customer will see too. Buy this place

Using Ninject in C# ASP.NET MVC5 Projects

1 1 1 1 1 Using Ninject in C# ASP.NET MVC5 Projects5.00Rating 4.50 (2 Votes)

The IoC containers are used for dependency injection. There are many IoC containers, we use Ninject, as it is easy to use and understand. You can install the required package via NuGet. The package is called Ninject.MVC5

After installing the package, we can already use Ninject in the project. For example, let's change the constructor of the controller as follows:


using Ninject;
//.....................
public class HomeController : Controller
{
    IRepository repo;
    public HomeController()
    {
        IKernel ninjectKernel = new StandardKernel();
        ninjectKernel.Bind<IRepository>().To<BookRepository>();
        repo = ninjectKernel.Get<IRepository>();
 
    }
    public ActionResult Index()
    {
        return View(repo.List());
    }
}

To manage dependencies through Ninject, one first needs to create a Ninject.IKernel object using the built-in implementation of this interface, the StandardKernel class:

IKernel ninjectKernel = new StandardKernel();

Next, you need to establish the relationship between the interfaces and their implementations:

ninjectKernel.Bind<IRepository>().To<BookRepository>();

This expression indicates that IRepository objects should be treated as BookRepository.

Finally, an interface object is created via the Get method:

repo = ninjectKernel.Get<IRepository>();

Since we have established a mapping between IRepository and BookRepository above, the ninjectKernel.Get<irepository>method will create an instance of the BookRepository class.

Global registration of dependencies

Let's register the dependencies globally for all controllers and for this we create a new Util folder in the project and put a new class NinjectRegistrations in it:


using DemoApp.Models;
using Ninject.Modules;
 
namespace IoSApp.Util
{
    public class NinjectRegistrations:NinjectModule
    {
        public override void Load()
        {
            Bind<IRepository>().To<BookRepository>();
        }
    }
}

The NinjectRegistrations class inherits from the NinjectModule class and actually represents the Ninject module. It overrides the method Load(), that is called when the module is loaded. And with the help of this call, the Bind<IRepository>().To<BookRepository>(), the actual mapping is established between the dependency interface and the concrete class of this interface.

Finally, it is necessary to initialize the dependency mapping with the start of our ASP.NET MVC application. How do we initialize dependency injection procedure? To do this, let's open to the Global.asax.cs file. This file is executed when the application starts. Let's change its content as follows:


using Ninject;
using Ninject.Modules;
using Ninject.Web.Mvc;
using DemoApp.Models;
using DemoApp.Util;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
 
namespace IoSApp
{
    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
 
            // Dependency injection
            NinjectModule registrations = new NinjectRegistrations();
            var kernel = new StandardKernel(registrations);
            DependencyResolver.SetResolver(new NinjectDependencyResolver(kernel));
        }
    }
}

This class is called when the application starts. At the end of the method, a Ninject module is created - the NinjectRegistrations object. And then the DependencyResolver.SetResolver() previously created dependency mapper is registered using the method .

And now let's change the controller:


public class HomeController : Controller
{
    IRepository repo;
    public HomeController(IRepository r)
    {
        repo = r;
    }
    public ActionResult Index()
    {
        return View(repo.List());
    }
}

Even though no specific implementation is passed to the controller constructor, everything will work. Let's consider step by step how dependency injection occurs in this case:

  1. MVC framework receives the request and accesses the HomeController
  2. The MVC framework calls on the dependency mapping class (in this case, the NinjectDependencyResolver class) to create a new HomeController object by passing the Type parameter to the GetService method (to the NinjectDependencyResolver class)
  3. The Dependency Mapper calls the Ninject framework to create a new HomeController, passing the type of the created object to the TryGet method
  4. Ninject looks at the HomeController constructor and sees that there is a dependency on the IRepository interface for which he sets up a mapping to a specific implementation
  5. Ninject creates an instance of the BookRepository class and then uses it to create the HomeController
  6. Ninject passes the generated HomeController object to the dependency mapper, which in turn passes it to the MVC framework. And then the request is processed.

 

Thus, we avoid using concrete implementations and work with objects at the interface level. And it is up to the NinjectDependencyResolver class to map interfaces to specific implementations.

Saturday the 25th.