AppSettings 未通过构造函数注入得到解决

AppSettings not getting resolved via constructor injection

我在appsettings.json中的配置如下:

{
"Logging": {
"IncludeScopes": false,
"LogLevel": {
  "Default": "Warning"
}
},
 "GatewaySettings": {
 "DBName": "StorageDb.sqlite",
 "DBSize": "100"    
 }
}   

这里是class代表配置数据

 public class GatewaySettings
 {
    public string DBName { get; set; }
    public string DBSize { get; set; }
 }

配置服务如下:

  services.AddSingleton(Configuration.GetSection("GatewaySettings").Get<GatewaySettings>());

但我收到此错误:

Value cannot be null. Parameter name: 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: Value cannot be null, Parameter name: implementationInstance

你应该使用 T

的 IOptions
services.Configure<GatewaySettings>(Configuration.GetSection("GatewaySettings"));

  public class SqlRepository
  {
    private readonly GatewaySettings _myConfiguration;
    public SqlRepository(IOptions<GatewaySettings> settingsAccessor)
    {
          _myConfiguration = settingsAccessor.Value;
    }
  }

你需要这些包

<PackageReference Include="Microsoft.Extensions.Options" Version="2.1.0" />
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="2.1.0" />

引用Options pattern in ASP.NET Core

不要将具体数据模型 class 添加到 DI - 使用 IOptions<> framework.

在您的启动中:

services.AddOptions();

// parses the config section into your data model
services.Configure<GatewaySettings>(Configuration.GetSection("GatewaySettings"));

现在,在您的 class 中:

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 才能获得此功能。