将参数从复合根向下传递到 DI 链

Passing parameters from composite root down the DI chain

我正在开发一个几乎没有依赖注入的项目,我想开始逐步添加它。

为了测试它,我想公开一个 API 端点,获取调用客户端传递给 API 方法的参数,创建组合根,然后向下传递参数连锁,链条。我使用的 IoC 容器是 Autofac。

我的问题基本上是从组合根将运行时参数传递给已解析服务的构造函数(API 的消费者传递的参数)的最佳方式是什么?还假设每个构造函数都接受传递给 API 的参数,我将如何通过所有服务的构造函数将参数传递到链下?

我在搜索答案时看到的答案涉及通过工厂。所以我会有这样的东西:

class Example
{
    private readonly ISftpClientFactory _clientFactory;

    public Example(ISftpClientFactory injectedFactory)
    {
        _clientFactory = injectedFactory;
    }

    public void DoTheWork()
    {
        var client = _clientFactory.GetClient(host, userName, password, timeout);
    }
}

这个答案的问题是我不知道DoTheWork中传递给GetClient的字符串参数,应该是通过构造函数从从 API 方法获取参数的组合根。

我在工厂看到的其他解决方案似乎总是在全局存储中(例如在文本框或会话中)提供可用信息。在我的例子中,我可以将参数保存在另一个 class 中,然后创建一个工厂以从该存储中检索,然后将该工厂向下传递,但这似乎有点矫枉过正并破坏了封装。

问题可以

Composition Root should not have to deal with runtime data. It only deals with fixed configuration values and the construction of components. As described in more detail here,运行时数据应该'flow'通过已经实例化的对象图的方法和属性:

Don't inject runtime data into application components during construction; it causes ambiguity, complicates the composition root with an extra responsibility and makes it extraordinarily hard to verify the correctness of your DI configuration. Instead, let runtime data flow through the method calls of constructed object graphs.