AppSettings无法通过构造函数注入解析

时间:2018-06-18 14:01:46

标签: c# asp.net-core dependency-injection 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&#39;

代码:

  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

2 个答案:

答案 0 :(得分:7)

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

在你的创业公司:

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

答案 1 :(得分:2)

您应该使用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