始终为空,c#,dependency-injection,asp.net-core-2.0,class-library,asp.net-core-mvc-2.0"/>

首页 > 解决方案 > Configuration.GetSection("ConnectionStringName").Get始终为空

问题描述

在我的 Asp.net Core 2.0 应用程序中,我试图按照@Nkosi here的建议实现在我的类库项目中不使用 IConfiguration 构造函数依赖项的连接字符串的设计。

在这种方法中,它无法将配置实例绑定到类型的新实例,如下面的代码行所示

public void ConfigureServices(IServiceCollection services) {
//...

var settings = Configuration
    .GetSection("ConnectionStrings:OdeToFood")
    .Get<ConnectionSetings>();

//...verify settings (if needed)

services.AddSingleton(settings);
}

public class ConnectionSetings
{
    public string Name { get; set; }
}

我可以看到Configuration.GetSection("ConnectionStrings:OdeToFood")返回“键”、“路径”和“值”属性,但它无法进行绑定并在设置中返回 null。

我见过类似的问题,其中 ppl 推荐了如下解决方案,但没有一个对我有用。

services.Configure<ConnectionsSetings>(Configuration.GetSection("ConnectionStrings:OdeToFood"));

还,

Configuration
    .GetSection("ConnectionStrings:OdeToFood").Bind<>

以下是 appsettings.json

{
"Greeting": "Hello!!!",
"ConnectionStrings": {
  "OdeToFood": "Server=(localdb)\\MSSQLLocalDB;Database=OdeToFood;Trusted_Connection=True;MultipleActiveResultSets=true"
  }
}

以下是 Configuration.GetSection 输出的即时窗口屏幕截图,我可以在其中看到键、路径和值

在此处输入图像描述

从下面的截图可以看出设置变量为空

在此处输入图像描述

标签: c#dependency-injectionasp.net-core-2.0class-libraryasp.net-core-mvc-2.0

解决方案


我不确定你想用提供的代码实现什么,但为了获得值而不是 null,你应该在 appsettings.json 中有以下部分:

{
  ...

  "ConnectionStrings": {
    "OdeToFood": {
      "Name": "someConncetionString"
    } 
  },

  ...
}

然后以下代码将返回该对象:

var settings = Configuration
    .GetSection("ConnectionStrings:OdeToFood")
    .Get<ConnectionSetings>();

推荐阅读