带有IOptionsMonitor <Settings>的GetService返回空对象

时间:2019-11-12 13:00:10

标签: c# asp.net-core asp.net-core-3.0

我在ASP.NET Core 3.0应用程序上具有以下内容:

IServiceCollection services = new ServiceCollection();

services.AddSingleton<Settings>(new Settings { DefaultPageSize = 40 });

IServiceProvider provider = services.BuildServiceProvider();

var result = provider.GetService<IOptionsMonitor<Settings>>();

最后一行resultnull ...知道为什么吗?

1 个答案:

答案 0 :(得分:2)

services.AddSingleton<Settings>(...

不会自动将SettingsIOptionsMonitor功能相关联。

需要使用选项模式扩展之一将Settings类配置为服务集合的选项

例如

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

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