gpt4 book ai didi

c# - 使用 MVC 3 Controller 的依赖注入(inject)的命令模式

转载 作者:行者123 更新时间:2023-11-30 22:23:50 24 4
gpt4 key购买 nike

我阅读了以下文章 .NET Junkie - Meanwhile... on the command side of my architecture这是另一位 stackoverflow 用户的建议,该用户概述了命令模式,并在文章末尾提供了如何将其与 DI 一起使用的策略。

这非常有帮助,但我缺少一件事,假设我创建了一个名为 CheckoutCustomerCommandHandler 的新类。

现在,假设我出于某种原因需要通过构造函数将此命令和 MoveCustomerCommandHandler 注入(inject)到 Controller 中。这对 DI 容器设置和构造函数有何影响?

在核心上,它们都实现了相同的接口(interface)。这似乎会导致 DI 容器的查找问题。在文章示例中,这是他们的示例注入(inject)器设置:

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<>));

最佳答案

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

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

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

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

关于c# - 使用 MVC 3 Controller 的依赖注入(inject)的命令模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13183598/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com