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

Mocking HttpCookieCollection in HttpRequestBase

When unit testing ASP.NET MVC2 projects the issue of injecting HttpContext is quickly encountered.  There seem to be many different ways / recommendations for mocking HttpContextBase to improve the testability of controllers and their actions.  My investigations into that will probably be a separate blog post in the near future but for now I want to cover something that had me stuck for longer than it probably should have.  That is how to mock non abstract/interfaced classes within HttpRequestBase and HttpResponseBase – namely the HttpCookieCollection class.   The code sample below illustrates how it can be used within a mocked instance of HttpRequestBase.  Cookies can be added / modified within the unit test code prior to being passed into the code being tested.   After it’s been called, using a combination of MOQ’s Verify and NUnit’s Assert it is possible to check how many times the collection is accessed (but you have to include the set up calls) and that the relevant cookies have …

Injecting HttpContextBase into an MVC Controller

It is a shame that when the ASP.NET MVC framework was released they did not think to build IoC support into the infrastructure. All the major components of the MVC engine appear to magically inherit instances of HttpContext and it’s related objects – which can cause no end of problems if you are trying to utilise Unit Testing and IoC. Reading around various articles on the subject just to get around this one problem requires the implementation of several different concepts and you are still left with a work around. The code below, along with the other links referenced in this article is my stab at resolving the issue. There’s probably nothing new here, but it does attempt to relate all the information needed to do this for Castle Windsor. The overview is that all controllers will need to inherit from a base controller, which takes an instance of HttpContext into it’s constructor. It then overrides the property HttpContext in the main controller class, supplying it’s own version…

Problem installing AWS CLI

It never feels like a good start when you're trying to start out with something and the install fails with an obscure error! I was just trying to install the Amazon CLI following the instructions at https://aws.amazon.com/cli/ and ran into the following error when running 'pip install awscli': Collecting awscli Could not find a version that satisfies the requirement awscli (from versions: ) No matching distribution found for awscli I appeared to have a correct version of Python installed (v2.7) and checking "PIP -v" indicated that 9.0.1 was installed. That all seemed to tick the required boxes but digging around a little more I did see that some people had had issues with various versions of PIP so I found / ran the following to upgrade to the latest vesion: curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py python get-pip.py This installed v9.0.3 of PIP which burst into life when I re-ran 'pip install awscli' and everything seems to be ok. Like…