我阅读了以下文章.NET Junkie - 同时...在我的架构的命令方面,这是由另一个 stackoverflow 用户提出的,该用户概述了命令模式并在文章末尾提供了如何将其与 DI 一起使用的策略。
这有很大帮助,但我缺少的一件事,假设我创建了一个名为CheckoutCustomerCommandHandler
.
现在,假设MoveCustomerCommandHandler
无论出于何种原因,我都需要通过构造函数将此命令和 注入控制器。这对 DI 容器设置和构造函数有何影响?
在核心,它们都实现了相同的接口。这似乎会导致 DI 容器的查找问题。在文章示例中,这是他们的样品注射器设置:
public interface ICommandHandler<TCommand>
{
void Handle(TCommand command);
}
// Exactly the same as before, but now with the interface.
public class MoveCustomerCommandHandler
: ICommandHandler<MoveCustomerCommand>
{
private readonly UnitOfWork db;
public MoveCustomerCommandHandler(UnitOfWork db,
[Other dependencies here])
{
this.db = db;
}
public void Handle(MoveCustomerCommand command)
{
// TODO: Logic here
}
}
// Again, same implementation as before, but now we depend
// upon the ICommandHandler abstraction.
public class CustomerController : Controller
{
private ICommandHandler<MoveCustomerCommand> handler;
public CustomerController(
ICommandHandler<MoveCustomerCommand> handler)
{
this.handler = handler;
}
public void MoveCustomer(int customerId,
Address newAddress)
{
var command = new MoveCustomerCommand
{
CustomerId = customerId,
NewAddress = newAddress
};
this.handler.Handle(command);
}
}
using SimpleInjector;
using SimpleInjector.Extensions;
var container = new Container();
// Go look in all assemblies and register all implementations
// of ICommandHandler<T> by their closed interface:
container.RegisterManyForOpenGeneric(
typeof(ICommandHandler<>),
AppDomain.CurrentDomain.GetAssemblies());
// Decorate each returned ICommandHandler<T> object with
// a TransactionCommandHandlerDecorator<T>.
container.RegisterDecorator(typeof(ICommandHandler<>),
typeof(TransactionCommandHandlerDecorator<>));
// Decorate each returned ICommandHandler<T> object with
// a DeadlockRetryCommandHandlerDecorator<T>.
container.RegisterDecorator(typeof(ICommandHandler<>),
typeof(DeadlockRetryCommandHandlerDecorator<>));