In my ASP.NET Core 3.1 application, I want to do some settings AT THE END since they are dependent on some other services being registered in the Startup.cs only. Can someone help me to understand why my class implementing the IPostConfigureOptions<T> is never invoked by .NET Core?
I have an Options class like this:
public class MyTestOptions
{
public string TestTest { get; set; }
}
This is used in the Startup.cs's ConfigureServices method as usual.
services.Configure<MyTestOptions>(o => { o.TestTest = "Test Test Test"; });
I need to change some settings "at the end". So, I implement IPostConfigureOptions<T> interface. The implementation class looks like this. (PostConfigure method not shown in the snippet below).
public class MyTestPostConfigure : IPostConfigureOptions<MyTestOptions>
This is then registered in the Startup.cs's ConfigureServices method as shown below.
services.ConfigureOptions<MyTestPostConfigure>();
I tried to register PostConfig class in different way too.
services.AddSingleton<IPostConfigureOptions<MyTestOptions>, MyTestPostConfigure>();
However, in any case the PostConfigure is not called.
Am I missing something?
**
Thanks to @KirkLarkin for the inputs he gave in the comments to my question.
The PostConfigure method on the MyTestPostConfigure class was not called because I was not accessing properties of MyTestOptions anywhere in my application.
I had injected IOptions<MyTestOptions> as a dependency in one of my classes and that's why constructor of the MyTestPostConfigure was called. However, since I was not using anything from the MyTestOptions class, .NET Core was not calling PostConfigure method.
As soon as accessed the TestTest property of the MyTestOptions class, I see that .NET Core executed both the Configure and PostConfigure.
In short, the execution of the Configure<TOptions> and IPostConfigureOptions<TOptions> is on-demand and it's delayed until you "actually use" the TOptions properties; merely injecting it as a dependency does not make .NET Core DI call the Configure and PostConfigure methods.
(I don't know on-demand configuration is documented anywhere or I missed this basic thing altogether.. )
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With