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

编程入门 行业动态 更新时间:2024-10-25 19:31:00
本文介绍了如何在Autofac中为开放的通用注册注册开放通用装饰器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

builder.RegisterAssemblyTypes(程序集)$ b在autofac中,处理程序的通用注册是这样的。 $ b .AsClosedTypesOf(typeof(ICommandHandler<>)) .AsImplementedInterfaces();

这可以正常工作,并为所有关闭类型注册所有处理程序。我现在想为所有处理程序注册一个通用装饰器,例如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中为开放的通用注册注册开放通用装饰器?

本文发布于:2023-11-04 12:24:35,感谢您对本站的认可!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:中为   如何在   Autofac

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!