While preparing some training material about ASP.NET Core, I was wondering about the difference between IOptionsMonitor and IOptionsSnapshot. In contrast to IOptions allow both interfaces to track configuration changes during the lifetime of your application.
However, internally both interfaces are constructed completely different; IOptionsMonitor
is registered in DI container as singleton, it has a CurrentValue
property and is capable of detecting changes through OnChange
event subscription. On the other hand, IOptionsSnapshot
is registered as scoped, has a Value
property and also have a change detection capability by reading the last options for each request, but it doesn't have the OnChange
event.
So what’s the point of having 2 interfaces with completely different signatures when both achieve the same goal; picking up configuration changes at runtime?
The difference between the two (and this also explains the different implementation approach) is that IOptionsSnapshot
guarantees that you have the same configuration values during a single request(explaining the scoped lifetime). IOptionsMonitor picks up every change immediately meaning that if the configuration value is read multiple times in a request, it can return different values.
As a general rule, you should prefer IOptionsSnaphot above IOptionsMonitor.