Moffen
Moffen

Reputation: 2003

.NET How to access TOptions during startup (Options Pattern)

I am using the .NET Options pattern to manage my configuration.

This configuration is needed in Controllers (easy with Dependency Injection) but also to configure other services during application startup.

I would have thought that the generic Services.Configure<MyOptionsClass> method would return an instance of MyOptionsClass but unfortunately it returns an IServiceCollection?

Is there a clean way to access a bound instance of MyOptionsClass here during startup?

var builder = WebApplication.CreateBuilder(args);

// Setup MyOptionsClass for DI
var unwantedServiceCollection = builder.Services.Configure<MyOptionsClass>(builder.Configuration.GetSection(MyOptionsClass.ConfigName));

// Already need to be able to access MyOptionsClass here:
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options => { options.Authority = instanceOfMyOptionsClass.Authority; });

Upvotes: 8

Views: 3904

Answers (1)

Parth Sekar
Parth Sekar

Reputation: 418

I had a similar need in the past and this is what I did:

var configOptions = builder.Configuration.GetSection(MyOptionsClass.ConfigName);

//You can also add data annotations to your config validate it on start
builder.Services
            .AddOptions<MyOptionsClass>()
            .Bind(configOptions)
            .ValidateDataAnnotations()
            .ValidateOnStart();

var configInstance = configOptions.Get<MyOptionsClass>();

Alternatively, you can use ServiceProviderServiceExtensions GetService<> or GetRequiredService<> to get the service you need by its type. Also, please be wary of using BuildServiceProvider which may create duplicate services as mentioned here.

Hope this helps.

Upvotes: 10

Related Questions