What is the difference between IOptions<T>, IOptionsSnapshot<T>, and IOptionsMonitor<T>, and which is safe to inject into a singleton?
Short answer
IOptions is registered as a singleton, computed once at first access and never refreshed even if configuration changes at runtime -- safe for singletons, suitable for genuinely static settings.
Advertisement
AModel answer
IOptions<T> is registered as a singleton, computed once at first access and never refreshed even if configuration changes at runtime -- safe for singletons, suitable for genuinely static settings. IOptionsSnapshot<T> is scoped, recomputed once per request, so injecting it into a singleton throws a captive dependency error. IOptionsMonitor<T> is a singleton that can notify subscribers immediately when configuration changes via OnChange, making it the correct choice for singleton services (like a BackgroundService) needing to react to live configuration updates.
// Safe in a singleton: reacts to changes via OnChange
public class MyBackgroundService(IOptionsMonitor<WorkerSettings> monitor) : BackgroundService {
protected override Task ExecuteAsync(CancellationToken ct) {
monitor.OnChange(settings => _logger.LogInformation("Settings changed!"));
return Task.CompletedTask;
}
}Real-world example
A long-running BackgroundService uses IOptionsMonitor to immediately pick up a changed polling interval from a hot-reloadable appsettings.json without needing to restart the entire application, something IOptions couldn't do at all.
Likely follow-ups
- Why can't a singleton service safely use IOptionsSnapshot?
- What triggers the OnChange callback in IOptionsMonitor specifically?
Related topics