以下を考えると:
public interface ICommandHandler<in TCommand>
{
void Handle(TCommand command);
}
public class MoveCustomerCommand
{
}
public class MoveCustomerCommandHandler : ICommandHandler<MoveCustomerCommand>
{
public void Handle(MoveCustomerCommand command)
{
Console.WriteLine("MoveCustomerCommandHandler");
}
}
public class TransactionCommandHandlerDecorator<TCommand> : ICommandHandler<TCommand>
{
private readonly ICommandHandler<TCommand> _decorated;
public TransactionCommandHandlerDecorator(ICommandHandler<TCommand> decorated)
{
_decorated = decorated;
}
public void Handle(TCommand command)
{
Console.WriteLine("TransactionCommandHandlerDecorator - before");
_decorated.Handle(command);
Console.WriteLine("TransactionCommandHandlerDecorator - after");
}
}
public class DeadlockRetryCommandHandlerDecorator<TCommand> : ICommandHandler<TCommand>
{
private readonly ICommandHandler<TCommand> _decorated;
public DeadlockRetryCommandHandlerDecorator(ICommandHandler<TCommand> decorated)
{
_decorated = decorated;
}
public void Handle(TCommand command)
{
Console.WriteLine("DeadlockRetryCommandHandlerDecorator - before");
_decorated.Handle(command);
Console.WriteLine("DeadlockRetryCommandHandlerDecorator - after");
}
}
次のコードを使用して をMoveCustomerCommandHandler
装飾できます。TransactionCommandHandlerDecorator
var builder = new ContainerBuilder();
builder.RegisterAssemblyTypes(typeof(MoveCustomerCommandHandler).Assembly)
.As(type => type.GetInterfaces()
.Where(interfaceType => interfaceType.IsClosedTypeOf(typeof(ICommandHandler<>)))
.Select(interfaceType => new KeyedService("commandHandler", interfaceType)));
builder.RegisterGenericDecorator(
typeof(TransactionCommandHandlerDecorator<>),
typeof(ICommandHandler<>),
fromKey: "commandHandler");
var container = builder.Build();
var commandHandler = container.Resolve<ICommandHandler<MoveCustomerCommand>>();
commandHandler.Handle(new MoveCustomerCommand());
どちらが出力されますか:
TransactionCommandHandlerDecorator - before
MoveCustomerCommandHandler
TransactionCommandHandlerDecorator - after
TransactionCommandHandlerDecorator
を で装飾してDeadlockRetryCommandHandlerDecorator
、次の出力を生成するにはどうすればよいですか
DeadlockRetryCommandHandlerDecorator- before
TransactionCommandHandlerDecorator - before
MoveCustomerCommandHandler
TransactionCommandHandlerDecorator - after
DeadlockRetryCommandHandlerDecorator- after