Monday, 2 September 2013

Three steps to configuring Ninject Dependency Injection

Ninject is an open source Dependency Injector for .NET.
  1.  Create MVC web application and add Ninject Dependencies to the project using nuget.  Modify controller code to declare a read-only member variable of your service and modify the constructor to introduce the service instance parameter as below:

    namespace DemoNinject.Controllers
    {
        public class HomeController : Controller
        {
            private readonly IVehicleService _vehicleService;

            public HomeController(IVehicleService vehicleService)
            {
                _vehicleService = vehicleService;
            }

            public ActionResult Index()
            {
                ViewBag.VehicleName = _vehicleService.GetVehicleName();

                return View();
            }
        }
    }
     
    I have IVehicleService interface and want to inject _vehicleService with the implementation
    IVehicleService


    using Ninject;

    namespace DemoNinject.ServiceLayer
    {
        public class VehicleService:IVehicleService
        {
            public string GetVehicleName ()
            {
                return "Your new vehicle : BMW";
            }
        }
    }
  2. Create NinjectDependencyResolver implementing IDependencyResolver as under, which will be responsible for injecting dependencies.

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    using Ninject;
    using Ninject.Syntax;

    namespace DemoNinject.Infrastructure
    {
        public class NinjectDependencyResolver : IDependencyResolver
        {
            private readonly IResolutionRoot _resolutionRoot;

            public NinjectDependencyResolver(IResolutionRoot kernel)
            {
                _resolutionRoot = kernel;
            }

            public object GetService(Type serviceType)
            {
                return _resolutionRoot.TryGet(serviceType);
            }

            public IEnumerable<object> GetServices(Type serviceType)
            {
                return _resolutionRoot.GetAll(serviceType);
            }

            public void Dispose()
            {
               
            }
        }
    }

  3. Setup Dependency resolver in Application_Start in Global.asax as under.

    public void SetupDependencyInjection()
    {
            // Create Ninject DI kernel
            IKernel kernel = new StandardKernel();

            // Register services with Ninject DI Container
            kernel.Bind<IVehicleRepository>().To<VehicleRepository>();

            // Tell ASP.NET MVC to use our Ninject DI Container
            DependencyResolver.SetResolver(new NinjectDependencyResolver(kernel));
    }

No comments:

Post a Comment