Tuesday, 28 September 2010

Updating NServiceBus to use another version of Castle Windsor

Having recently taken a look at NServiceBus, the first obstacle that I encountered was that it was not compatible with the version of Castle Windsor which we were using.  Luckily due to the design of NServiceBus adding a new version of an IoC framework is relatively painless if you follow a couple of basic steps and follow the format laid out by the existing framework.  Whilst the NServiceBus documentation say what you need to do, it does not say why or how.  It probably took longer than it should for me to realise that I could easily download the source code and modify the existing Castle Windsor object builder instance for the version that we were using. 

As recommended within NServiceBus I created a new VS project called “NServiceBus.ObjectBuilder.CastleWindsor.2.5.0” adding a reference to the Castle binaries we would be using (as you may have guessed from the project name, that was v2.5.0).  The project only needed two classes defined (Windsor250ObjectBuilder & ConfigureWindsorBuilder) the code for which is listed below.   Please feel free to copy / modify this code as needed – if you find any obvious issues please let me know.  As I’m only just starting out with NServiceBus and Castle Windsor, I’m not sure if I will be able to assist much – but at the very least I can either update this article with a relevant note or improvement.

namespace NServiceBus.ObjectBuilder.CastleWindsor
{
    usingSystem;
    usingSystem.Collections.Generic;
    usingSystem.Linq;
    usingCastle.MicroKernel.Releasers;
    usingCommon;
    usingCastle.Windsor;
    usingCastle.MicroKernel;
    usingCastle.Core;
    usingCastle.MicroKernel.Registration;

    /// <summary>
    ///
Castle Windsor implementaton of IContainer.
  
/// </summary>
  
public classWindsor250ObjectBuilder: IContainer
  
{
        /// <summary>
        ///
The container itself.
      
/// </summary>
      
publicIWindsorContainer Container { get; set; }

        /// <summary>
        ///
Instantites the class with a new WindsorContainer setting the NoTrackingReleasePolicy.
      
/// </summary>
      
publicWindsor250ObjectBuilder()
        {
            Container = newWindsorContainer();
            Container.Kernel.ReleasePolicy = newNoTrackingReleasePolicy();
        }

        /// <summary>
        ///
Instantiates the class saving the given container.
      
/// </summary>
        /// <param name="container"></param>
      
publicWindsor250ObjectBuilder(IWindsorContainer container)
        {
            Container = container;
        }

        voidIContainer.Configure(TypeconcreteComponent, ComponentCallModelEnum callModel)
        {
            var handler = GetHandlerForType(concreteComponent);
            if(handler == null)
            {
                var lifestyle = GetLifestyleTypeFrom(callModel);

                var reg = Component.For(GetAllServiceTypesFor(concreteComponent)).ImplementedBy(concreteComponent);
                reg.LifeStyle.Is(lifestyle);

                Container.Kernel.Register(reg);
            }
        }

        voidIContainer.ConfigureProperty(Typecomponent, stringproperty, objectvalue)
        {
            var handler = GetHandlerForType(component);
            if(handler == null)
                throw newInvalidOperationException("Cannot configure property for a type which hadn't been configured yet. Please call 'Configure' first.");

            handler.AddCustomDependencyValue(property, value);
        }

        voidIContainer.RegisterSingleton(TypelookupType, objectinstance)
        {
            //Container.Kernel.AddComponentInstance(Guid.NewGuid().ToString(), lookupType, instance);
          
Container.Register(Component.For(lookupType).Named(Guid.NewGuid().ToString()).Instance(instance));
        }

        objectIContainer.Build(TypetypeToBuild)
        {
            try
          
{
                returnContainer.Resolve(typeToBuild);
            }
            catch(ComponentNotFoundException)
            {
                return null;
            }
        }

        IEnumerable<object> IContainer.BuildAll(TypetypeToBuild)
        {
            returnContainer.ResolveAll(typeToBuild).Cast<object>();
        }

        private staticLifestyleType GetLifestyleTypeFrom(ComponentCallModelEnum callModel)
        {
            switch(callModel)
            {
                caseComponentCallModelEnum.Singlecall: returnLifestyleType.Transient;
                caseComponentCallModelEnum.Singleton: returnLifestyleType.Singleton;
            }

            returnLifestyleType.Undefined;
        }

        private staticIEnumerable<Type> GetAllServiceTypesFor(Typet)
        {
            if(t == null)
                return newList<Type>();

            var result = newList<Type>(t.GetInterfaces()) { t };

            foreach (var interfaceType int.GetInterfaces())
                result.AddRange(GetAllServiceTypesFor(interfaceType));

            returnresult;
        }

        privateIHandler GetHandlerForType(TypeconcreteComponent)
        {
            returnContainer.Kernel.GetAssignableHandlers(typeof(object))
                .Where(h => h.ComponentModel.Implementation == concreteComponent)
                .FirstOrDefault();
        }
    }
}

namespace NServiceBus
{
using ObjectBuilder.Common.Config;
using Castle.Windsor;

using ObjectBuilder.CastleWindsor;

/// <summary>
///
Contains extension methods to NServiceBus.Configure.
/// </summary>
public static class ConfigureWindsorBuilder
{
/// <summary>
///
Use the Castle Windsor builder with the NoTrackingReleasePolicy.
/// </summary>
/// <param name="config"></param>
/// <returns></returns>
public static Configure CastleWindsor250Builder(this Configure config)
{
ConfigureCommon.With(config, new Windsor250ObjectBuilder());

return config;
}

/// <summary>
///
Use the Castle Windsor builder passing in a preconfigured container to be used by nServiceBus.
/// </summary>
/// <param name="config"></param>
/// <param name="container"></param>
/// <returns></returns>
public static Configure CastleWindsor250Builder(this Configure config, IWindsorContainer container)
{
ConfigureCommon.With(config, new Windsor250ObjectBuilder(container));

return config;
}
}
}


del.icio.us Tags: ,

3 comments:

wayne-o said...

that code is completely mashed :s

Paul Hadfield said...

Thanks, looks like a job for the weekend - bit of reformatting needed

wayne-o said...

:) cheers for doing that :)

Post a Comment