Search code examples
c#dependency-injectionasp.net-core-2.0class-libraryasp.net-core-mvc-2.0

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

enter image description here

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

enter image description here


Solution

  • 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>();