Skip to main content

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: ,

Comments

  1. that code is completely mashed :s

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

    ReplyDelete
  3. :) cheers for doing that :)

    ReplyDelete

Post a Comment

Popular posts from this blog

Why do my Android Notification only appear in the status bar?

I'm definitely getting back into Android development, I'm remembering that feeling of 'Surely this should be easier than this!'. All I wanted to do was to schedule a local notification which behaved similar to a push notification pop-up. That is, as well as showing the small icon in the status bar I wanted it to pop up on screen to notify the end user. All seems fairly easily, I found this code for how to schedule a notification. That all worked perfectly, apart from the notification would only appear in the status bar. Searching around I found loads of different answers / solutions, mostly all saying the same thing:It only worked if you used 'NotificationCompat.Builder' in place of 'Notification.Builder', orYou had to set the priority to 'NotificationCompat.PRIORITY_HIGH'As usually happens, none of these solutions worked for me until I added in the missing piece of the jigsaw:- '.setDefaults(Notification.DEFAULT_ALL)'. For me this…

Do "Task Hours" add anything in Scrum (Agile)?

What do task hours add to the overall process in scrum?This was a question that has arisen from all team members in both instances that I've helped teams switch over to scrum. The benefits of artifacts like the comparative story point estimation, the 2 week sprints, stand-ups and the end of sprint demo have been self evident to the team, but as one I think every team member has expressed dismay when it comes to task planning and estimating each task in hours. Left unchecked there is a natural tendency for people to actually begin to dread the start of each sprint purely due to the task planning session.In my current role we've been lucky to investigate this further as a team.The team sat down to discuss the problems it was experiencing with estimating tasks in hours and the following common themes appeared:It is hard: Maybe it shouldn't be, but time estimation is hard! Story points are comparative and abstracted making them easier to determine, but time estimate is gen…

IPhone hangs when running from XCode

I've had this happen a couple of times now and the first time was a little worrying that I'd bricked my iPhone. Basically I was running an application on my phone via XCode and when rebuilding an updated version it failed with a "busy" error message. Stopping XCode and unconnecting my phone had no effect, the phone was stuck displaying the loading screen of the application and wouldn't respond to any key commands. To fix you have to hard reboot, holding the power and home button until the phone reboots - doesn't lose any of the data you have on your phone (a concern the first time I did it).