In ASP.Net Core 7, our program file uses extensions that needs values from a configuration file. We decided to go with the Microsoft implementation of the Option pattern as described briefly here. Since we need some values before the app is built, we create and bind an instance of our options class as described.
DemoOptions.cs
public class DemoOptions
{
public const string SectionName = "Demo";
[Required]
[NotNull]
public string? Name { get; set; }
[Required]
[NotNull]
public string? Uri { get; set; }
}
Program.cs
var demoOptions = new DemoOptions();
builder.Configuration.GetSection(DemoOptions.SectionName).Bind(demoOptions);
builder.Services.AddThisService(demoOptions);
AddThisService.cs (extension)
public static void AddThisService(this IServiceCollection services, DemoOptions options)
{
// Some sample code
var x = options.Name
}
That's great. But also need to register it to the DI (because some class will have it injected later) and to validate configurations values on start (based on data annotation as you've seen). For this we can use AddOptions
var demoOptions = new DemoOptions();
builder.Configuration.GetSection(DemoOptions.SectionName).Bind(demoOptions);
builder.Services.AddOptions<DemoOptions>()
.Configure<IConfiguration>(
(options, configuration) =>
configuration.GetSection(DemoOptions.SectionName).Bind(options))
.ValidateDataAnnotations()
.ValidateOnStart();
builder.Services.AddThisService(demoOptions);
As you can see it's quite verbose and, above all, you have to create 2 instances of your DemoOptions : 1 for immediate use and the other for DI registration (under OptionBuilder.Configure when you bind the section). All of this was already done in the lines before. I didn't find any way to register an existing instance to OptionBuilder AddOptions or Configure extensions. Do you have any idea how can I make this a little better (instance creation for immediate reading, DI registration and options validations)?