Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET Core 3.1 does not call PostConfigure on the class implementing IPostConfigureOptions<T>

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? **

  1. Why the PostConfigure is never executed?
  2. Isn't it true that all IPostConfigureOptions get executed automatically during startup? Or is there any case when .NET Core chooses not to run it until it's actually required?**
like image 817
Learner Avatar asked Aug 12 '20 12:08

Learner


1 Answers

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.. )

like image 73
Learner Avatar answered Nov 15 '22 01:11

Learner