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

时间:2015-02-19 10:31:20

标签: c# generics 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");

任何帮助表示赞赏。

2 个答案:

答案 0 :(得分:2)

我和你一样,并没有工作;然后找到解决方案。 截至Boby Johnson - Gist

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

答案 1 :(得分:0)

根据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");