我閱讀了另一個stackoverflow用戶提出的以下文章.NET Junkie - Meanwhile... on the command side of my architecture,該用戶概述了命令模式,並提供瞭如何在文章結尾使用DI的策略。使用依賴注入MVC 3控制器的命令模式
這非常有幫助,但我錯過了一件事,比方說我創建了一個名爲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<>));
看起來這是一個'SimpleInjector'特定的問題。我可以告訴你像Ninject和Autofac這樣的其他DI容器支持這種情況。 – neontapir