- 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 implementationIVehicleServiceusing Ninject;namespace DemoNinject.ServiceLayer{public class VehicleService:IVehicleService{public string GetVehicleName (){return "Your new vehicle : BMW";}}}
- 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(){}}}
- Setup Dependency resolver in Application_Start in Global.asax as under. public void SetupDependencyInjection(){// Create Ninject DI kernelIKernel kernel = new StandardKernel();// Register services with Ninject DI Containerkernel.Bind<IVehicleRepository>().To<VehicleRepository>();// Tell ASP.NET MVC to use our Ninject DI ContainerDependencyResolver.SetResolver(new NinjectDependencyResolver(kernel));}
Monday, 2 September 2013
Three steps to configuring Ninject Dependency Injection
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment