1

In the main program class, I want to use the Option pattern to read, validate and register Option objects to the DI so it can be injected in different objects at runtime.

Here is what it looks like

public class MyTestOptions
{
    public const string MyTestSectionName = "MyTestSection";

    public string Property1 { get; set; } = String.Empty;
    public string Property2 { get; set; } = String.Empty;
}

Program.cs

var myTestConfigurationSection = builder.Configuration.GetSection(MyTestOptions.MyTestSectionName);
// Registers a configuration instance which MyTestOptions binds against
builder.Services.Configure<MyTestOptions>(myTestConfigurationSection);

builder.Services.AddOptions<MyTestOptions>(MyTestOptions.MyTestSectionName)
    .Bind(myTestConfigurationSection)
    .ValidateDataAnnotations()
    .ValidateOnStart();

var myTestOptions = new MyTestOptions();
storageConfigurationSection.Bind(myTestOptions);
builder.Services.AddSomething(myTestOptions);


var app = builder.Build();

MyOwnThing.cs

public class MyOwnThing : IThing
{
    private readonly string _property1;

    public MyOwnThing(IOptionsMonitor<MyTestOptions> options)
    {
        _property1 = options.CurrentValue.Property1;
    }

    public async Task DoSomething()
    {
        var x = DoSomethingElse(_property1);
    }

    private DoSomethingElse(string propValue) 
    {
        // Some code would go here
    }
}

If I run this, the injection is done well and I get the value from my appsettings.json "Property1" inside the MyThing class at runtime. I tought that the "AddOptions" would register the MyTestOptions so I wouldn't need the line "builder.Services.Configure...". But if I remove this line, I get the default string.Empty value in my class at runtime. What am I doing wrong here? I want to be able to bind the object, validate values and inject it in the DI.

Note that I read the answer here but it's not quite clear to me.

Patrice Cote
  • 3,572
  • 12
  • 43
  • 72

0 Answers0