Sunday 1 September 2013

Wire up a chain of responsibility with Castle Windsor

As part of the greenfield project I'm currently working on I decided that I'd use the chain of responsibility design pattern, but it took me a little while to work out how to set up Castle Windsor to support this.  It's pretty simple, but the stuff I found on the interwebs all seemed to be slightly out of date, so I thought I'd explain it here.

The short version is you can use the 'DependsOn' and 'Dependency.OnComponent<T, U>' methods when registering your components to do this pretty easily.  You can use an installer that looks something like this:
public class ChainOfResponsibilityInstaller : IWindsorInstaller
{
 public void Install(IWindsorContainer container, IConfigurationStore store)
 {
  container.Register(Component.For<IChainItem>()
         .ImplementedBy<ChainItemOne>()
         .DependsOn(Dependency.OnComponent<IChainItem,ChainItemTwo>()),
         Component.For<IChainItem>()
          .ImplementedBy<ChainItemTwo>()
          .DependsOn(Dependency.OnComponent<IChainItem, ChainItemThree>()),
         Component.For<IChainItem>()
           .ImplementedBy<ChainItemThree>());
 }
}

I've put a very basic project up on GitHub - https://github.com/StephenFriend/ChainOfResponsibility-with-Castle - to demonstrate an actual working solution.