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));
    }

Sunday 1 September 2013

Three steps to configuring Castle Windsor Dependency Injection



 Assuming you are aware of dependency injection concept and you have used any dependency injection earlier, I would like to show how to configure CastleWindsor dependency injection in 3 easy steps.

* I am not a regular blogger so might not be able to respond your queries.

1. Add below configuration in web.config file


<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <section name="castle" type="Castle.Windsor.Configuration.AppDomain.CastleSectionHandler,Castle.Windsor" />
  </configSections>
 
  <castle>
    <components>
      <component id="VehicleRepository" service="DemoCastleWindor.Models.IWebRepository,DemoCastleWindor" type="DemoCastleWindor.Models.WebRepository,DemoCastleWindor" lifestyle="PerWebRequest" />
      <component id="VehicleDataService" service="Demo.Repository.IVehicleRepository,Demo.Repository" type="Demo.Repository.VehicleRepository,Demo.Repository" lifestyle="PerWebRequest" />
    </components>
  </castle>
</configuration>

In above configuration services contains fully qualified namespace of Interface separated by project name containing Interface. Type contains namespace and class implementing Interface.

2. Create WindsorControllerFactory to inject dependent classes

using System;
using System.Linq;
using System.Web.Mvc;
using Castle.Core;
using Castle.Windsor;
using Castle.Windsor.Configuration.Interpreters;
using Castle.Core.Resource;
using System.Reflection;

namespace DemoCastleWindor.Infrastructure
{
        public class WindsorControllerFactory : DefaultControllerFactory
        {
            private WindsorContainer container;

            public WindsorControllerFactory()
            {
                this.container = new WindsorContainer(
                    new XmlInterpreter(new ConfigResource("castle"))
                );
                var controllerTypes = from t in Assembly.GetExecutingAssembly().GetTypes()
                                      where typeof(IController).IsAssignableFrom(t)
                                      select t;

                foreach (Type t in controllerTypes)
                    this.container.AddComponentLifeStyle(t.FullName, t, LifestyleType.Transient);
            }


            protected override IController GetControllerInstance(System.Web.Routing.RequestContext requestContext, Type controllerType)
            {
                return (IController)this.container.Resolve(controllerType);
            }
        }
    }

3. Create WindsorControllerFactory to inject dependent classes

In global.asax, configure controller factory to create the new instance of controller.
ControllerBuilder.Current.SetControllerFactory(typeof(WindsorControllerFactory));