c# - AppSettings 未通过构造函数注入解决
问题描述
我的配置appsettings.json
如下:
{
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Warning"
}
},
"GatewaySettings": {
"DBName": "StorageDb.sqlite",
"DBSize": "100"
}
}
这是表示配置数据的类
public class GatewaySettings
{
public string DBName { get; set; }
public string DBSize { get; set; }
}
配置服务如下:
services.AddSingleton(Configuration.GetSection("GatewaySettings").Get<GatewaySettings>());
但我收到此错误:
值不能为空。参数名称: implementationInstance'
代码:
public class SqlRepository
{
private readonly GatewaySettings _myConfiguration;
public SqlRepository(GatewaySettings settings)
{
_myConfiguration = settings;
}
}
依赖注入代码:
var settings = new IOTGatewaySettings();
builder.Register(c => new SqlRepository(settings))
背景
我将 ASPNET CORE 应用程序作为 Windows 服务托管,.NET Framework 是 4.6.1
注意:类似的问题出现在这里,但没有提供解决方案。System.ArgumentNullException:值不能为空,参数名称: implementationInstance
解决方案
不要将具体的数据模型类添加到 DI - 使用IOptions<>
框架。
在您的启动中:
services.AddOptions();
// parses the config section into your data model
services.Configure<GatewaySettings>(Configuration.GetSection("GatewaySettings"));
现在,在你的课堂上:
public class SqlRepository
{
private readonly GatewaySettings _myConfiguration;
public SqlRepository(IOptions<GatewaySettings> gatewayOptions)
{
_myConfiguration = gatewayOptions.Value;
// optional null check here
}
}
注意:如果您的项目不包含该Microsoft.AspNetCore.All
包,则需要添加另一个包Microsoft.Extensions.Options.ConfigurationExtensions
才能获得此功能。
推荐阅读
- swift - 在 Bazel 中集成 AudioKit (Swift CocoaPod)
- c++ - 如何更改结构中变量的值?
- r - 自动填充 r 中的列
- vue.js - Vue Jest 错误找不到带有 node_modules 路径的模块,解析器未定义
- azure - 在 azure 管道任务 HelmDeploy@0 中引用 helm 集的值
- javascript - 三个 js 中心 Object3D 进入场景中心,切出网格
- c++ - 如何修复 Visual Studio 2019 中出现的 0xc000007b 错误?
- r - 在列中查找字符变量
- python - 盈透证券 API 放置期权价差订单给出错误验证请求
- terminal - ROS/Linux:linux终端中的“&”到底是什么?