我在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>>();
最后一行result
是null
...知道为什么吗?
答案 0 :(得分:2)
services.AddSingleton<Settings>(...
不会自动将Settings
与IOptionsMonitor
功能相关联。
需要使用选项模式扩展之一将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>>();