Pages

Tuesday, May 31, 2011

Quick Windsor Example

Castle.Windsor, an IoC container, can be implemented in multiple ways. Here is one of them. I find it rather simple and flexible. Here is a quick example on how to get it up and running in a project.

The code is only a few lines:

        private void RegisterIoC()
        {
            var container = new WindsorContainer(
                new XmlInterpreter(new FileResource("castle.config")));

            var outboundMessageHandlerStrategy = container.Resolve<IOutboundMessageHandlerStrategy>();
        }

The configuration is read from castle.config file, where the components are configured. This allows for flexibility and making the module replacement a configuration change instead of code change.

The castle.config looks like:

<?xml version="1.0"?>
<configuration>
  <components>
    <component id="taxcalc.service" 
               type="IoC.Tutorials.Part1.TaxCalculator, IoC.Tutorials.Part1" />
  </components>
</configuration>

The type name and namespace do not match the code above, btw, but the principle is there.

Another other option would be to use fluent interface to configure the container, as below.

            container.Register(Component.For<IOutboundMessageHandlerStrategy>()
                .ImplementedBy<WCFOutboundMessageHandlerStrategy>().Named("blah"));

At the moment, this is the work in progress. I'll get to finalize this example when I'm back to the task that involves Windsor.

 

No comments: