这可以正常工作,并为所有关闭类型注册所有处理程序。我现在想为所有处理程序注册一个通用装饰器,例如a
LoggingCommandHandlerDecorator<>从autofac文档看,您需要命名实现,以便装饰器可以是默认的ICommandHandler。我不确定在注册开放式泛型时这是如何工作的。我已经尝试在开放注册中添加一个名字。
builder.RegisterAssemblyTypes(程序集) .AsClosedTypesOf(typeof(ICommandHandler<>))。命名(commandHandler,typeof(ICommandHandler<>)) .AsImplementedInterfaces();注册装饰器但没有快乐。
builder.RegisterGenericDecorator(typeof(LoggingCommandHandlerDecorator<>),typeof(ICommandHandler<>), fromKey: commandHandler);任何帮助表示赞赏。根据 autofac 文档解决方案 //docs.autofac/en/latest/advanced/adapters-decorators.htmlrel =nofollow>这里,请尝试以下解决方案:
// //使用名称注册开放泛型,以便 //装饰器可以使用它。 builder.RegisterGeneric(typeof(CommandHandler<>)) .Named(commandHandler,typeof(ICommandHandler<>)); //注册泛型装饰器,以便它可以包装 //已解析的已命名泛型。 builder.RegisterGenericDecorator( typeof(LoggingCommandHandlerDecorator<>), typeof(ICommandHandler<>), fromKey:commandHandler);
I have an open generic registration for handlers in autofac that looks like this.
builder.RegisterAssemblyTypes(assemblies) .AsClosedTypesOf(typeof (ICommandHandler<>)) .AsImplementedInterfaces();This works fine and registers all my handlers for there closed types. I now want to register a generic decorator for all of the handlers e.g. a
LoggingCommandHandlerDecorator<>In look from autofac documentation that you need to name your implementation so the decorator can be the default ICommandHandler. I'm not sure how this works when you are registering open generics. I've tried adding a named to the open registration.
builder.RegisterAssemblyTypes(assemblies) .AsClosedTypesOf(typeof (ICommandHandler<>)) .Named("commandHandler", typeof (ICommandHandler<>)) .AsImplementedInterfaces();And registering the decorator but no joy.
builder.RegisterGenericDecorator(typeof (LoggingCommandHandlerDecorator<>), typeof (ICommandHandler<>), fromKey: "commandHandler");Any help appreciated.
解决方案As per the autofac documentation here, please try following solution:
// 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");
更多推荐
如何在Autofac中为开放的通用注册注册开放通用装饰器?
发布评论