问题
I have a generic command handler with many concrete implementations.
public interface ICommandHandler<TCommand>
I have a decorator with a type constraint that I want to use for multiple, but not all, implementations of the ICommandHandler
public class AddNoteCommandHandlerDecorator<TCommand>
: ICommandHandler<TCommand> where TCommand : INoteCommand
{
private readonly ICommandHandler<TCommand> decorated;
public AddNoteCommandHandlerDecorator(ICommandHandler<TCommand> decorated)
{
this.decorated = decorated;
}
public void Handle(TCommand command)
...
I am trying to register with AutoFac as follows:
public static void Register(HttpConfiguration config)
{
var builder = new ContainerBuilder();
builder.RegisterControllers(typeof(MvcApplication).Assembly);
var assemblies = AppDomain.CurrentDomain.GetAssemblies();
builder.RegisterAssemblyTypes(assemblies)
.As(t => t.GetInterfaces()
.Where(a => a.IsClosedTypeOf(typeof(ICommandHandler<>)))
.Select(a => new KeyedService("commandHandler", a)));
builder.RegisterGenericDecorator(
typeof(AddNoteCommandHandlerDecorator<>),
typeof(ICommandHandler<>),
fromKey: "commandHandler");
var container = builder.Build();
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
config.DependencyResolver = new AutoFacContainer(new AutofacDependencyResolver(container));
}
However, when a concrete command handler is called on a command that implements INoteCommand, the decorator is not functioning.
Have I mis-configured the registration in AutoFac? Or did I miss something else?
来源:https://stackoverflow.com/questions/28727607/autofac-registergenericdecorator-not-working-with-decorator-having-type-constrai