我有两个装饰器:
class DbCommandWithTransactionHandlerDecorator<TCommand>
: IDbCommandHandler<TCommand> { ... }
class DbOptimisticConcurrencyRetryDecorator<TCommand>
: IDbCommandHandler<TCommand> { ... }
这些装饰器将事务管理和乐观并发重试功能添加到数据库命令。
我使用 Autofac 作为我的 IoC 容器。我想设置 Autofac 以便它自动连接所有IDbCommandHandler<>
在程序集中找到的东西,这样当我请求说 an 时IDbCommandHandler<CreateNewNotificationCommand>
,它会自动先用 a 装饰它DbCommandWithTransactionHandlerDecorator
,然后用a 装饰它DbOptimisticConcurrencyRetryDecorator
。
我一直在尝试用 Autofac 来解决这个问题builder.RegisterGenericDecorator()
,但还没有成功。主要问题是装饰器需要一个“命名”参数才能工作。下面是最“接近”我想要实现的示例代码 - 但是主要缺陷是我仍然必须手动注册类型。
var builder = new ContainerBuilder();
var a = Assembly.GetExecutingAssembly();
// I need to find a way how these can be 'auto-wired',
// rather than having to manually wire each command.
builder.RegisterType<CreateNewNotificationCommandHandler>()
.Named<IDbCommandHandler<CreateNewNotificationCommand>>("command");
builder.RegisterType<CreateNewNotificationCommandHandler_2>()
.Named<IDbCommandHandler<CreateNewNotificationCommand_2>>("command");
builder.RegisterGenericDecorator(
typeof(DbCommandWithTransactionHandlerDecorator<>),
typeof(IDbCommandHandler<>),
fromKey: "command");
var container = builder.Build();
var handler1 =
container.Resolve<IDbCommandHandler<CreateNewNotificationCommand>>();
var handler2 =
container.Resolve<IDbCommandHandler<CreateNewNotificationCommand_2>>();
handler1.Handle(null); //these are correctly decorated
handler2.Handle(null); //these are correctly decorated