Registering many like types in Castle Windsor

Castle Windsor is an awesome dependency injection framework available for use with .NET. While a full explanation of dependency injection is beyond the scope of this post, two key reasons to use a dependency injection framework are:

1) Code using dependency injection is less “tightly-coupled” and thus less brittle.
2) Dependency injection is vital in order to achieve true test driven development (incorporating unit-testing and mocking).

Anyone familiar with Castle Windsor will know that individual types can be registered as follows:

container.Register(
                Component.For<IUserRepository>()
                .ImplementedBy(typeof(UserRepository))
                .LifeStyle.Transient);

However, it is often the case that we have many “like” classes in an application, all providing similar functionality and having a similar naming convention. A good example would be respository classes, particularly when using ORM frameworks. Rather than manually adding each repository to the dependency container, Castle Windsor has a neat shortcut for registering multiple classes:

container.Register(Classes.FromAssemblyContaining(typeof(UserRepository))
                .Where(type => type.Name.EndsWith("Repository"))
                .If(type => type.Namespace.StartsWith("MyApplication.Api.Data.Repositories"))
                .WithService.FromInterface(typeof(IRepository))
                .Configure(c => c.LifestyleTransient()));

The code above will find all classes implementing the interace IRepository in the namespace MyApplication.Api.Data.Repositories (and its children) that have Repository at the end of their name. These can then be accessed at runtime using:

var userRepository = injector.Resolve<IUserRepository>();
var productRepository = injector.Resolve<IProductRepository>();

Very cool!

Leave a Reply

Your email address will not be published. Required fields are marked *