Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 )

like image 224
Robin Avatar asked Dec 30 '25 23:12

Robin


2 Answers

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

var settings = builder.Configuration
    .GetSection(ApiConfiguration.Api)
    .Get<ApiConfiguration>();
like image 84
Guru Stron Avatar answered Jan 02 '26 11:01

Guru Stron


so I can use the appSettings values when adding some Services to the ServiceCollections.

This sounds wrong to me as IOptions are part of DI container and can be injected in the constructor.

builder.Services.AddScoped<Service>();

...

public class Service
{
    private readonly ApiConfiguration myOptions;
    
    public Service(IOptions<ApiConfiguration> options)
    {
        myOptions = options.Value;
    }
}

If your class can't rely on IOptions like in the example below

public class Service
{
    private readonly ApiConfiguration myOptions;
    
    public Service(ApiConfiguration options)
    {
        myOptions = options;
    }
}

, use a factory method instead:

builder.Services.AddScoped<ApiConfiguration>(sp => sp.GetRequiredService<IOptions<ApiConfiguration>>().Value);
builder.Services.AddScoped<Service>();

OR

builder.Services.AddScoped<Service>(sp => new Service(sp.GetRequiredService<IOptions<ApiConfiguration>>().Value));
like image 22
Yegor Androsov Avatar answered Jan 02 '26 13:01

Yegor Androsov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!