Miguel Moura
Miguel Moura

Reputation: 39474

GetService with IOptionsMonitor<Settings> returns null object

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

Answers (1)

Nkosi
Nkosi

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>>();

Reference Options pattern in ASP.NET Core: Configure simple options with a delegate

Upvotes: 5

Related Questions