如何在 Autofac 中为开放通用注册注册一个开放通用装饰器?

How to register an open generic decorator for an open generic registration in Autofac?

我在 autofac 中有一个处理程序的开放式通用注册,如下所示。

  builder.RegisterAssemblyTypes(assemblies)
     .AsClosedTypesOf(typeof (ICommandHandler<>))
     .AsImplementedInterfaces(); 

这工作正常并为那里的封闭类型注册了我的所有处理程序。我现在想为所有处理程序注册一个通用装饰器,例如一个

LoggingCommandHandlerDecorator<>

从 autofac 文档中可以看出,您需要为您的实现命名,以便装饰器可以是默认的 ICommandHandler。当您注册开放泛型时,我不确定它是如何工作的。我试过在公开注册中添加一个名字。

  builder.RegisterAssemblyTypes(assemblies)
            .AsClosedTypesOf(typeof (ICommandHandler<>))
            .Named("commandHandler", typeof (ICommandHandler<>))
            .AsImplementedInterfaces();

并注册装饰器但没有快乐。

 builder.RegisterGenericDecorator(typeof (LoggingCommandHandlerDecorator<>), typeof (ICommandHandler<>),
          fromKey: "commandHandler");

感谢任何帮助。

根据 autofac 文档 here,请尝试以下解决方案:

// Register the open generic with a name so the
// decorator can use it.
builder.RegisterGeneric(typeof(CommandHandler<>))
            .Named("commandHandler", typeof(ICommandHandler<>));

// Register the generic decorator so it can wrap
// the resolved named generics.
builder.RegisterGenericDecorator(
            typeof(LoggingCommandHandlerDecorator<>),
            typeof(ICommandHandler<>),
            fromKey: "commandHandler");

我和你一样,没有工作;然后在下面找到解决方案。 通过 Boby Johnson - Gist

    builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly())
       .As(type => type.GetInterfaces()
           .Where(interfaceType => interfaceType.IsClosedTypeOf(typeof(ICommandHandler<,>)))
           .Select(interfaceType => new KeyedService("commandHandler", interfaceType)))
       .InstancePerLifetimeScope();