Difference between IOptionsMonitor vs. IOptionsSnapshot
The comments have some pretty good answers already. To try and summarize/repeat Tseng:
IOptionsSnapshot
is great for getting injected into an object that is scoped or transient. It will be consistent for the lifetime of that object and new values will come in as you get new objects.
However, if you need options that reload in a singleton, IOptionsMonitor
is what you should use, because your singleton will never change. A good example of such services are those inherited from IHostedService
, for long-running background services in ASP.NET Core.
IOptionsMonitor
is a singleton service that retrieves current option values at any time, which is especially useful in singleton dependencies.
IOptionsSnapshot
is a scoped service and provides a snapshot of the options at the time the IOptionsSnapshot<T>
object is constructed. Options snapshots are designed for use with transient and scoped dependencies.
Use
IOptions<T>
when you are not expecting your config values to change. UseIOptionsSnaphot<T>
when you are expecting your values to change but want it to be consistent for the entirety of a request. UseIOptionsMonitor<T>
when you need real time values.