Constant result from `Predicate<DecoratorPredicateContext>`

Coordinator
Nov 7, 2013 at 8:37 PM
Is it possible to vary the results of the Predicate<DecoratorPredicateContext> that is evaluated by the RegisterDecorator method?

I have a very simple test class that contains a static variable:
private static Type typeToDecorate = null;
And I have registered my classes and decorator like so:
container.RegisterAllOpenGeneric(
    typeof(ICommandHandler<>),
    typeof(CommandHandler1<>),
    typeof(CommandHandler2<>));

container.RegisterDecorator(
    typeof(ICommandHandler<>),
    typeof(CommandHandlerDecorator<>),
    c => c.ImplementationType == typeToDecorate);
What I've found it is that the call GetAllInstances will only evaluate the decorators the first time.

In the code below I set things up to decorate CommandHandler1 and make a call to GetAllInstances. I then set things up to have CommandHandler2 decorated but the second call to GetAllInstances returns the same results as the first call. I.e. CommandHandler1 is decorated and not CommandHandler2.
typeToDecorate = typeof(CommandHandler1<Command>);

var result = container
    .GetAllInstances<ICommandHandler<Command>>()
    .ToList();

typeToDecorate = typeof(CommandHandler2<Command>);

result = container
    .GetAllInstances<ICommandHandler<Command>>()
    .ToList();
Have I misunderstood something?
Coordinator
Nov 7, 2013 at 8:54 PM
> What I've found it is that the call GetAllInstances will only evaluate the decorators the first time.

Absolutely. The XML docs aren't really clear about this, but the predicate will just be evaluated once per closed generic type. This is by design and allows optimizing performance. What you want is to apply decorators dynamically based on runtime conditions. For more information about how to do this, please read Applying decorators at runtime using Simple Injector.
Marked as answer by qujck on 11/8/2013 at 12:02 AM
Coordinator
Nov 7, 2013 at 10:26 PM
Edited Nov 8, 2013 at 7:02 AM
Thanks - it looks to be exactly what I need.