首页 > 解决方案 > 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

标签: c#asp.net-coredependency-injectionappsettings

解决方案


不要将具体的数据模型类添加到 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才能获得此功能。


推荐阅读