当您可以在没有它的情况下进行 DI 设置时,IServiceCollection 的 Configure 方法的目的是什么?

What is the purpose of the Configure method of IServiceCollection when you can DI settings without it?

我已经这样做了:

services.Configure<ApplicationSettings>(_configuration.GetSection("ApplicationSettings"));

我原以为这可以让我注射 ApplicationSettings,但显然不行。

我可以做 GetSection(...) 并将其注册为单例,但是 .Configure 有什么意义?

msdn 文档说“注册 TOptions 将绑定的配置实例,并在配置更改时更新选项。”

虽然我不清楚如何设置模式以在我的应用程序中将配置用作 DI。

这是我试图实现的 SO 问题:

这正是为强类型设置部分配置依赖注入 ApplicationSettings.

public void ConfigureServices(IServiceCollection services)
{
    // ...

    services.Configure<ApplicationSettings>(_configuration.GetSection("ApplicationSettings"));

    // You can register your service
    services.AddTransient<SomeService>();
}

然后您实现该服务,并自动将设置部分注入其中。

public class SomeService
{
    private readonly IOptions<ApplicationSettings> _options;

    public SomeService(IOptions<ApplicationSettings> options)
    {
        _options = options;
    }

    public string AddPrefix(string value)
    {
        // AddPrefix("test value")
        // will return:
        // PREFIX - test value
        return $"{_options.Value.Prefix} - {value}";
    }
}

鉴于您的 ApplicationSettings 定义为:

public class ApplicationSettings
{
    public string Prefix { get; set; }
}

你的 appsettings.json 应该是这样的:

{
    "ApplicationSettings": {
        "Prefix": "PREFIX"
    }
}