如何在 ASP.NET Core 6 中创建构建器之前读取 IConfiguration

0 c# .net-core asp.net-core asp.net-core-6.0

我正在使用以这种方式创建构建器的库

var webApiOptions = new AkaAppOptions<ApiOptions>(ApplicationId, authenticationType);
var builder = new AkaAppBuilder<ApiOptions>(args, webApiOptions);
Run Code Online (Sandbox Code Playgroud)

现在这个构建器包含IConfiguration我需要的。

我的问题是我需要阅读配置才能知道authenticationType它是什么类型。这发生在我有一个WebApplicationBuilder.

我的选择是创建临时的WebApplicationBuilder,读取配置,然后创建这个库生成器,我猜这里的缺点是内存。

另一种选择是手动读取appsettings.json以获取该信息/缺点是内存和内存环境应用程序设置?

读哪一篇

例如,我会做这样的事情来创建临时构建器,而不是我需要的构建器

var tempBuilder = WebApplication.CreateBuilder(args);
var useExternalAuth = tempBuilder.Configuration.GetSection("ExternalAuth").Exists();
var authenticationType = useExternalAuth ? AuthenticationType.ExternalService : AuthenticationType.Service;

var webApiOptions = new AkaAppOptions<ApiOptions>(ApplicationId, authenticationType);
var builder = new AkaAppBuilder<ApiOptions>(args, webApiOptions);
Run Code Online (Sandbox Code Playgroud)

还有其他选择吗?

Mar*_*kus 5

如果只是关于(临时)配置,您可以设置ConfigurationBuilder并添加所需的提供程序,例如:

IConfiguration config = new ConfigurationBuilder()
    .AddJsonFile("appsettings.json")
    .AddEnvironmentVariables()
    .Build();
// ... use temporary config
Run Code Online (Sandbox Code Playgroud)

通过调用构建,IConfiguration对象被组装,您可以在应用程序的设置阶段使用它。

有关 .NET Core 中配置概念的详细信息,请参阅此链接