2

我阅读了以下文章.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<>));
4

1 回答 1

2

这是你的类声明的样子......

public class CheckoutCustomerCommandHandler :
    ICommandHandler<CheckoutCustomerCommand> {...}

public class MoveCustomerCommandHandler : 
    ICommandHandler<MoveCustomerCommand> {...}

这些可能看起来它们实现了相同的接口,但它们实际上编译为两个不同的接口,因为泛型参数不同。您的 DI 框架将能够区分它们。

于 2012-11-01T19:11:23.520 回答