使用命令模式时的依赖注入

Ben*_*ter 13 .net dependency-injection command-pattern

我第一次使用命令模式.我有点不确定我应该如何处理依赖项.

在下面的代码中,我们调度一个CreateProductCommand然后排队等待稍后执行的代码.该命令封装了执行所需的所有信息.

在这种情况下,我们可能需要访问某种类型的数据存储来创建产品.我的问题是,如何将此依赖项注入命令以便它可以执行?

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

非常感谢
Ben

eul*_*rfx 15

查看代码后,我建议不要使用命令模式,而是使用命令数据对象和命令处理程序:

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

    }
}
Run Code Online (Sandbox Code Playgroud)

此方案更适用于CreateProductCommand可能需要跨越应用程序边界的情况.此外,您可以通过DI容器解析CreateProductCommand实例,并配置所有依赖项.调度程序或"消息总线"在收到命令时将调用处理程序.

看看这里的一些背景信息.