Wiring Up Generics In Castle Windsor


I’m working with a new team that has a slightly different technology stack then I’m used to.  On most projects where I am the team lead, StructureMap is my IOC container of choice.  I’ve always thought that this was just laziness on my part because I can wire up most things very quickly. Now I’m beginning to think that SM has spoiled me 🙂

I like to take advantage of open generic mapping that most of the popular containers support.  In this particular case, I’ve got a Generic Validator that takes in a different array of validations for a given type.

 

The constructor for this guy looks like this:

public class ServiceValidationRunner : IServiceValidationRunner     {         private IValidation[] _validations;         private readonly IValidationErrorHandler _errorHandler;

        public ServiceValidationRunner(IValidation[] validations, IValidationErrorHandler errorHandler)         {             _validations = validations;             _errorHandler = errorHandler;         }        … }

Here is how I’m am setting this up for two different types that have different validations:

container.Register
            (
                //wire up the specific types with their validation rules
                Component.For<IServiceValidationRunner>().ImplementedBy<ServiceValidationRunner>()                     .DependsOn(new {validations = new[]{new Validator1(),new Validator2}}),                 Component.For<IServiceValidationRunner>().ImplementedBy<ServiceValidationRunner>()                     .DependsOn(new {validations = new[]{new Validator1(), new Validator3()}}),             … );

The code is pretty self explanatory, it’s a simple matter of wiring up the dependencies for the specific type the generic class is wired up for.

Demeter Helps You Fend Off the One True Constant: Change