Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Options lifecycle in ASP.NET Core dependency injection

Which lifetime cycle has the configuration object got when it's registered the following way? Is it a singleton, transient or scoped?

  {
      services.Configure<SomeConfiguration>(configuration.GetSection(nameof(SomeConfiguration)));
  }

This is how I get the configuration into my service class

public class SomeService: ISomeService
{
    public SomeService(IOptionsMonitor<SomeConfiguration> configuration)
    {
         _configuration = configuration.CurrentValue;
    }
}

Its is very to hard know from debugging it if its a singleton or not. Because IOptionsMonitor is able to detect changes on run time by running a watcher on appsettings.json changed

like image 748
user14346079 Avatar asked Jan 23 '26 06:01

user14346079


1 Answers

IOptions

IOptionsSnapshot:

  • Is useful in scenarios where options should be recomputed on every request.
  • Is registered as Scoped and therefore cannot be injected into a Singleton service.

IOptionsMonitor:

  • Is used to retrieve options and manage options notifications for TOptions instances.
  • Is registered as a Singleton and can be injected into any service lifetime.

Reference

like image 193
Farhad Zamani Avatar answered Jan 24 '26 18:01

Farhad Zamani



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!