Difference between IOptions, IOptionsSnapshot and IOptionsMonitor In Asp.netCore
The Options pattern uses classes to provide strongly typed access to groups of related settings and helps to satisfy Encapsulation and Separation of concerns principals .options also provide a mechanism to validate configuration data.
For a better understanding there is code with each interface.consider following Appsettings.json file:
and ApplicationSettings.cs file:
then in Startup.cs
IOptions
IOptions interface works as a Singleton and can be injected into all services with any lifetime. After running the program , if anything change in “appsettings.json” , IOptions gives the same data and values as before.
IOptionsSnapshot
IOptionsSnapshot interface works as Scoped so for each request reads appsettings.json . this interface can be injected in Scoped or Transient services therefore can’t be injected into a Singleton service.
IOptionsSnapshot is useful in scenarios where options should be recomputed on every request.
Consider following code:
result is :
now open “appsettings.json” and change port form 27610 to 27613 then call API again.result is :
IOptionsMonitor
IOptionsMonitor interface works as a Singleton and like IOptions can be injected in any service lifetime.this interface supports reloading the changed configurations after app has started ,so if a change is made to the appsettings.json file, new changes can be received by the OnChange method
after change appsettings.json and save it
Resources :