Conditions:
I have a generic command handler:
public interface ICommand<TResult> : IValidatableObject
{
}
public interface ICommandHandler<TCommand, TResult>
where TCommand : ICommand<TResult>, IValidatableObject
{
TResult Handle(TCommand command);
}
I have a decorator that I want to use for multiple, but not all, implementations of the ICommandHandler (I am going to use a custom attribute to differentiate handlers):
public sealed class LoggingDecorator<TCommand, TResult> : ICommandHandler<TCommand, TResult>
where TCommand : ICommand<TResult>, IValidatableObject
{
private readonly ICommandHandler<TCommand, TResult> _handler;
public LoggingDecorator(ICommandHandler<TCommand, TResult> handler)
{
_handler = handler;
}
public TResult Handle(TCommand command)
{
var test = 0;
return _handler.Handle(command);
}
}
I am trying to register them with AutoFac as follows:
builder.RegisterAssemblyTypes(ThisAssembly)
.AsClosedTypesOf(typeof(ICommandHandler<,>))
.AsImplementedInterfaces();
builder.RegisterGenericDecorator(
decoratorType: typeof(LoggingDecorator<,>),
serviceType: typeof(ICommandHandler<,>),
condition: _decoratorContext =>
{
return false; // true;
});
Seems like the condition is ignored, the decorator is "assigned" to all handlers always. Have I mis-configured the registration in AutoFac? Or did I miss something else?
How to achieve that the decorator is not registered if the condition returns 'false' in RegisterGenericDecorator method ?
Autofac 4.9.1 is a pretty old version now (3+ yrs). I know that some behaviour around decorator conditions was fixed in v6.0.0; see this issue where upgrading fixed someone's problem that sounds similar to yours.
I'd suggest upgrading to the latest version; if upgrading doesn't fix it, put together a minimal repro and raise an issue on our github repo.