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


No comments:

Post a Comment