AutoFac RegisterGenericDecorator not working with decorator having type constraint

二次信任 提交于 2020-01-03 18:34:30

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!