Wednesday, May 19, 2010

How to auto-register types in Castle Windsor

This is how you can use Castle Windsor's fluent interface to auto-register all the types within one or more assemblies:

private static void RegisterTypes(WindsorContainer container)
{
        var assemblies = GetAssembliesToRegister();
 
        foreach (var assembly in assemblies)
        {
            container.Register(
                    AllTypes.Pick().FromAssemblyNamed(assembly)
                    .If(x => x.IsPublic)
                    .If(x => x.GetInterfaces().Length > 0)
                    .Configure(x => x.LifeStyle.Transient)
                    .WithService.FirstInterface()
                    );
        }
}
private static List GetAssembliesToRegister()
{
        var assemblies = new List();
 
        assemblies.Add("DemoApp.DataAccess");
 assemblies.Add("DemoApp.BusinessLogic");
 
        return assemblies;
}