如何在 .NET6 的 Program.cs 中,在 builder.build() 之前使用 IOptions 模式?

Rob*_*bin 14 .net c# .net-core .net-6.0

使用 .NET6 中的选项模式,我可以访问一些配置值,如下所示:

builder.Services.Configure<ApiConfiguration>(
    builder.Configuration.GetSection(ApiConfiguration.Api));

var app = builder.Build();

var options = app.Services.GetRequiredService<IOptions<ApiConfiguration>>().Value;
Run Code Online (Sandbox Code Playgroud)

但是,我想在 builder.Build() 之前获取选项,以便在向 ServiceCollections 添加一些服务时可以使用 appSettings 值。

我还没能在任何地方找到它,所以我想知道它是否可能(当然还有如何:D)

Gur*_*ron 13

在默认的 DI 容器服务中,在构建之前无法解析服务,并且不建议多次构建容器(出于多种原因)。如果您在构建应用程序之前需要设置,您可以在不使用选项模式的情况下访问它们:

var settings = builder.Configuration
    .GetSection(ApiConfiguration.Api)
    .Get<ApiConfiguration>();
Run Code Online (Sandbox Code Playgroud)