I am using the options pattern inside of my application, reading properties from my appsettings.json file and using them in classes throughout my application.
However, I have a case where I need to use these properties inside of my program.cs file itself. Here is code which does not work since I am not able to inject an instance of the config within the program.cs file. The code shows what I would like to happen... is there a better way of doing this and still staying within the options pattern?
builder.Services.Configure<SwaggerConfig>(builder.Configuration.GetSection("Swagger"));
var app = builder.Build();
app.UseSwagger();
app.UseSwaggerUI(s =>
{
s.SwaggerEndpoint( SwaggerConfig.Url ,
SwaggerConfig.Name);
s.RoutePrefix = SwaggerConfig.RoutePrefix;
});
You have access to the IServiceProvider
within your code. You can obtain the configuration you are looking for with app.Services.GetRequiredService<IOptions<SwaggerConfig>>().Value
.
The thing is, once you call builder.Build()
, the DI container will be also built.