Castle Windsor for StructureMap users

This page is targeted towards people who already know StructureMap container, and want to get up to speed with Castle Windsor. You will quickly learn about major differences between the two, and how best you can reuse what you already know about StructureMap.

Bootstrapping your application

A common technique for using StructureMap is to have a static Bootstrapper class that initialises the static, ObjectFactory container, often by adding instances of type Registry. For example:

  1. public static class Bootstrapper
  2. {
  3. public static void Configure()
  4. {
  5. ObjectFactory.Initialize(x => x.AddRegistry<MyAppRegistry>());
  6. }
  7. }

The entry point to the application will call the Bootstrapper to initialize the container, and then resolve the type or types needed to start running the application using ObjectFactory.GetInstance<T>().

  1. Bootstrapper.Configure();
  2. var shell = ObjectFactory.GetInstance<IApplicationShell>();
  3. shell.Show();

With Windsor the standard approach is to bootstrap a single instance of the container at the entry point of the application and resolve types from that. Windsor’s equivalent to a Registry is an installer — a class which implements IWindsorInstaller. The following code will create a new container and install all public IWindsorInstaller implementations in the current assembly into the container.

  1. public IWindsorContainer BootstrapContainer()
  2. {
  3. return new WindsorContainer()
  4. .Install( FromAssembly.This() );
  5. }

This will be used in the entry point to the application in a similar way to StructureMap. Windsor’s equivalent to GetInstance<T>() is Resolve<T>().

  1. var container = BootstrapContainer();
  2. var shell = container.Resolve<IApplicationShell>();
  3. shell.Show();

See Three Calls Pattern for the details and recommendations on how to bootstrap the Windsor container.

From Registry to Installer

For StructureMap type mappings are configured in the constructor of a Registry sub-class (this example uses the StructureMap 2.6+ syntax).

  1. class MyAppRegistry : Registry
  2. {
  3. public MyAppRegistry()
  4. {
  5. For<IFoo>().Use<Foo>();
  6. For<IBar>().Use<Bar>();
  7. }
  8. }

For Windsor this is done by implementing the Install method of the IWindsorInstaller interface.

  1. public class MyAppInstaller : IWindsorInstaller
  2. {
  3. public void Install(IWindsorContainer container, IConfigurationStore store)
  4. {
  5. container.Register(
  6. Component.For<IFoo>().ImplementedBy<Foo>(),
  7. Component.For<IBar>().ImplementedBy<Bar>()
  8. );
  9. }
  10. }

Auto-wiring: scanning with conventions

StructureMap has a Scan() method in the Registry base class to automatically add type mappings based on various conventions. A common convention is to map implementations to interfaces based on name (e.g. map IFoo as implemented by Foo):

  1. public MyAppRegistry()
  2. {
  3. Scan(x =>
  4. {
  5. x.TheCallingAssembly();
  6. x.WithDefaultConventions();
  7. });
  8. //No longer required (will be wired up by convention):
  9. //For<IFoo>().Use<Foo>();
  10. //For<IBar>().Use<Bar>();
  11. }

For Windsor we do this by picking types using a specific service.

  1. public class MyAppInstaller : IWindsorInstaller
  2. {
  3. public void Install(IWindsorContainer container, IConfigurationStore store)
  4. {
  5. container.Register(
  6. AllTypes.FromThisAssembly().Pick()
  7. .WithService.DefaultInterface()
  8. .Configure(c => c.Lifestyle.Transient);
  9. //No longer required (will be wired up by convention):
  10. //Component.For<IFoo>().ImplementedBy<Foo>(),
  11. //Component.For<IBar>().ImplementedBy<Bar>()
  12. );
  13. }
  14. }

Adding dependencies

To add a dependency to an auto-wired component, you need to use ConfigureFor:

  1. container.Register(
  2. AllTypes.FromThisAssembly().Pick()
  3. .WithService.DefaultInterface()
  4. .ConfigureFor<ISomething>(c => c.DependsOn(new[] {
  5. Property.ForKey("someKey").Eq("someValue"),
  6. })
  7. );

Resolving collections

When multiple implementations of a single interface are registered with StructureMap, then an instance of each implementation will be injected when a collection of that type is requested. For example, if we have these mappings:

  1. For<IFoo>().Use<ThisFoo>();
  2. For<IFoo>().Use<ThatFoo>();

then ObjectFactory.GetInstance<IEnumerable<IFoo>>() will yield an instance of ThisFoo and an instance of ThatFoo.

This behaviour needs to be explicitly configured for Windsor by adding a Resolver. The following configuration will return an array containing ThisFoo and ThatFoo when an array of IFoo is resolved (container.Resolve<IFoo[]>()).

  1. public void Install(IWindsorContainer container, IConfigurationStore store)
  2. {
  3. container.Kernel.Resolver.AddSubResolver(new CollectionResolver(container.Kernel));
  4. container.Register(
  5. Component.For<IFoo>().ImplementedBy<ThisFoo>(),
  6. Component.For<IFoo>().ImplementedBy<ThatFoo>()
  7. AllTypes.FromThisAssembly().Pick().WithService.DefaultInterface();
  8. );
  9. }

Namespaces

Windsor partitions components into a number of different namespaces. Here is a quick summary of the namespaces used so far.

Behaviour Required namespaces
Creating a container (new WindsorContainer().Install()) Castle.Windsor
Basic installer (implementing IWindsorInstaller) Castle.Windsor, Castle.MicroKernel.Registration, Castle.MicroKernel.SubSystems.Configuration
Resolvers Castle.MicroKernel.Resolvers and sub-namespaces like SpecializedResolvers which include ArrayResolver

Lifestyle (instance scope)

What’s called an instance scope in StructureMap, Windsor calls Lifestyle, as specified in the LifestyleType enum.

StructureMap Windsor Notes
Singleton Singleton This is the default lifestyle in Windsor
PerRequest Transient Windsor keeps references to transient components!
ThreadLocal PerThread
HttpContext PerWebRequest
HttpSession None/Custom There’s no direct equivalent in Windsor for this lifestyle, but implementing one is trivial
Hybrid None/Custom There’s no direct equivalent in Windsor for this lifestyle, but implementing one is trivial

ConnectImplementationsToTypesClosing

StructureMap has ConnectImplementationsToTypesClosing that can used to register non-generic types with their base generic service. How can I do that with Windsor?

  1. kernel.Register(AllTypes.FromAssembly(Assembly.GetExecutingAssembly())
  2. .BasedOn(typeof(ICommand<>))
  3. .WithService.Base());

Registering single type with multiple services

You can easily register single component type, to satisfy more than one service in Castle Windsor. For the follwing StructureMap code:

  1. ForRequestedType<IEventStoreUnitOfWork<IDomainEvent>>()
  2. .CacheBy(InstanceScope.Hybrid)
  3. .TheDefault.Is.OfConcreteType<EventStoreUnitOfWork<IDomainEvent>>();
  4. ForRequestedType<IUnitOfWork>()
  5. .TheDefault.Is.ConstructedBy(x => x.GetInstance<IEventStoreUnitOfWork<IDomainEvent>>());

Corresponding Windsor code would be:

  1. container.Register(
  2. Component.For<IUnitOfWork, IEventStoreUnitOfWork<IDomainEvent>>()
  3. .ImplementedBy<EventStoreUnitOfWork<IDomainEvent>>().LifeStyle.PerWebRequest
  4. );

The ability to register component with multiple services is called Type Forwarding, and can be also set from XML configuration.