使用命令模式时,依赖注入命令、模式

2023-09-04 22:55:46 作者:天会亮、心会暖

我使用的是命令模式的第一次。我有点不确定,我应该如何处理的依赖关系。

I'm using the Command Pattern for the first time. I'm a little unsure how I should handle dependencies.

在下面的code,我们派出一个 CreateProductCommand ,然后排队在稍后的时间执行。该命令封装了所有需要执行的信息。

In the code below, we dispatch a CreateProductCommand which is then queued to be executed at a later time. The command encapsulates all the information it needs to execute.

在这种情况下,很可能,我们将需要访问某种类型的数据存储来创建产品。我的问题是,我怎么这种依赖注入命令,使其可以执行?

In this case it is likely we will need to access a data store of some type to create the product. My question is, how do I inject this dependency into the command so that it can execute?

public interface ICommand {
    void Execute();
}

public class CreateProductCommand : ICommand {
    private string productName;

    public CreateProductCommand(string productName) {
        this.ProductName = productName;
    }

    public void Execute() {
        // save product
    }
}

public class Dispatcher {
    public void Dispatch<TCommand>(TCommand command) where TCommand : ICommand {
        // save command to queue
    }
}

public class CommandInvoker {
    public void Run() {

        // get queue

        while (true) {
            var command = queue.Dequeue<ICommand>();
            command.Execute();
            Thread.Sleep(10000);
        }
    }
}

public class Client {
    public void CreateProduct(string productName) {
        var command = new CreateProductCommand(productName);
        var dispatcher = new Dispatcher();
        dispatcher.Dispatch(command);
    }
}

非常感谢 本

Many thanks Ben

推荐答案

在看着你的code,我建议不使用命令模式,而是转而使用命令数据对象和命令处理程序:

After looking at your code I would recommend not using the command pattern, but instead using command data objects and a command handler:

public interface ICommand { }

public interface ICommandHandler<TCommand> where TCommand : ICommand
{
void Handle(TCommand command);
}

public class CreateProductCommand : ICommand { }

public class CreateProductCommandHandler : ICommandHandler<CreateProductCommand>
{
public void Handle(CreateProductCommand command)
{
}
}

这场景更适合的情况下CreateProductCommand可能需要跨越应用程序边界。另外,还可以有CreateProductCommand通过与配置的所有相关性的DI容器解决了一个实例。调度员,或信息总线将调用该处理程序当它接收到的命令。

This scenario is more suitable for cases where CreateProductCommand might need to cross application boundaries. Also, you can have an instance of CreateProductCommand resolved by a DI container with all dependencies configured. The dispatcher, or 'message bus' would invoke the handler when it receives the command.

看看这里一些背景资料。