【问题标题】:Dependency Injection when using the Command Pattern使用命令模式时的依赖注入
【发布时间】:2011-09-30 20:54:45
【问题描述】:

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

在下面的代码中,我们调度了一个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);
    }
}

非常感谢

【问题讨论】:

    标签: .net dependency-injection command-pattern


    【解决方案1】:

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

    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 可能需要跨越应用程序边界的情况。此外,您可以使用配置了所有依赖项的 DI 容器解析 CreateProductCommand 的实例。调度程序或“消息总线”将在收到命令时调用处理程序。

    查看here 了解一些背景信息。

    【讨论】:

    猜你喜欢
    • 2012-10-22
    • 1970-01-01
    • 2016-10-05
    • 1970-01-01
    • 2020-05-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多