Reputation: 39474
I have the following on an ASP.NET Core 3.0 application:
IServiceCollection services = new ServiceCollection();
services.AddSingleton<Settings>(new Settings { DefaultPageSize = 40 });
IServiceProvider provider = services.BuildServiceProvider();
var result = provider.GetService<IOptionsMonitor<Settings>>();
On the last line result
is null
... Any idea why?
Upvotes: 2
Views: 2248
Reputation: 247433
services.AddSingleton<Settings>(...
Does not automatically associate Settings
with the IOptionsMonitor
feature.
Need to configure that Settings
class as an option with the service collection using one of the Options pattern extensions
For example
IServiceCollection services = new ServiceCollection();
// Options bound and configured by a delegate
services.Configure<Settings>(option => {
option.DefaultPageSize = 40;
});
IServiceProvider provider = services.BuildServiceProvider();
var result = provider.GetService<IOptionsMonitor<Settings>>();
Upvotes: 5