'How to use IOptions pattern in Program.cs in .NET6, before builder.build()?

Using the options pattern in .NET6, I can get access to some config values as follows:

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

var app = builder.Build();

var options = app.Services.GetRequiredService<IOptions<ApiConfiguration>>().Value;

However, I would like to get the Options before builder.Build(), so I can use the appSettings values when adding some Services to the ServiceCollections.

I haven't been able to find it anywhere yet, so I am wondering if it is even possible (and how ofcourse :D )



Solution 1:[1]

In the default DI container services can't be resolved before it is build and building container multiple times is not a recommended approach (for multiple reasons). If you need settings before the application is build you can access them without options pattern:

var settings = builder.Configuration.GetSection(ApiConfiguration.Api).Get<ApiConfiguration>();

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Guru Stron