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

kud*_*ger 3 c# dependency-injection appsettings asp.net-core

我的配置appsettings.json如下:

{
"Logging": {
"IncludeScopes": false,
"LogLevel": {
  "Default": "Warning"
}
},
 "GatewaySettings": {
 "DBName": "StorageDb.sqlite",
 "DBSize": "100"    
 }
}   
Run Code Online (Sandbox Code Playgroud)

这是表示配置数据的类

 public class GatewaySettings
 {
    public string DBName { get; set; }
    public string DBSize { get; set; }
 }
Run Code Online (Sandbox Code Playgroud)

配置服务如下:

  services.AddSingleton(Configuration.GetSection("GatewaySettings").Get<GatewaySettings>());
Run Code Online (Sandbox Code Playgroud)

但我收到这个错误:

值不能为空.参数名称:implementationInstance'

码:

  public class SqlRepository
  {
        private readonly GatewaySettings _myConfiguration;

        public SqlRepository(GatewaySettings settings)
        {
              _myConfiguration = settings;
        }
  }
Run Code Online (Sandbox Code Playgroud)

依赖注入代码:

var settings = new IOTGatewaySettings();
builder.Register(c => new SqlRepository(settings))
Run Code Online (Sandbox Code Playgroud)

背景

我将ASPNET CORE应用程序作为Windows服务托管,而.NET Framework是4.6.1

注意:此处出现类似问题但未提供解决方案.System.ArgumentNullException:Value不能为null,参数名称:implementationInstance

gun*_*171 8

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

在你的创业公司:

services.AddOptions();

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

现在,在你的课堂上:

public class SqlRepository
{
    private readonly GatewaySettings _myConfiguration;
    public SqlRepository(IOptions<GatewaySettings> gatewayOptions)
    {
        _myConfiguration = gatewayOptions.Value;
        // optional null check here
    }
}
Run Code Online (Sandbox Code Playgroud)

注意:如果您的项目不包含该Microsoft.AspNetCore.All软件包,则需要添加另一个软件包Microsoft.Extensions.Options.ConfigurationExtensions才能获得此功能.