简体   繁体   中英

Configuration.GetSection(“ConnectionStringName”).Get<?> always null

In my Asp.net Core 2.0 application, I am trying to implement the design of not to use the IConfiguration constructor dependency for connection strings in my class library project as advised by @Nkosi here .

In this approach it is unable to bind the configuration instance to the new instance of type as in the following lines of code

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; }
}

I can see Configuration.GetSection("ConnectionStrings:OdeToFood") returning the "Key", "Path" and "Value" attributes but it fails to do the bindings and return null in settings.

I have seen similar questions where ppl have recommended solutions like as follow but none of them is working for me.

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

Also,

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

Following is the appsettings.json

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

Following is the immediate window screen shot of Configuration.GetSection output where I can see Key, Path and Value

在此处输入图片说明

From the following screenshot it can be seen the setting variable is coming null

在此处输入图片说明

I'm not sure what you want to achieve with provided code, but in order to get value instead of null, you should have the following section in your appsettings.json:

{
  ...

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

  ...
}

Then the following code will return the object:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM