Search code examples
c#configurationbindingappsettings

C# bind whole appSettings file to class


In C# we can bind some settings in appSettings to class, for example like that:

var connectionStrings = new ConnectionStrings();
var sectionConnectionString = Configuration.GetSection("ConnectionStrings");

In appsettings it looks like below:

{
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "AllowedHosts": "*",
  "ConnectionStrings": {

And when I want to bind Logging I need to call another bind:

Configuration.GetSection("Logging");

How can I bind whole appsettings file? GetSection with empty string doesn't work:

Configuration.GetSection("");

Solution

  • You need a Class for your config and afterwards you can use this (You do not need to map every setting, just the ones you need):

    var configObject = Configuration.Get<ConfigObject>();
    

    Example config object:

    public class ConfigObject {
        public Logging Logging { get; set; } 
        public string AllowedHosts { get; set; } 
        public ConnectionStrings ConnectionStrings { get; set; } 
    }
    
    public class Logging {
        public LogLevel LogLevel { get; set; } 
    }
    
    public class LogLevel {
        public string Default { get; set; } 
    }
    
    public class ConnectionStrings {
        public string ConnString1 { get; set; } 
    }
    

    Hint: if you're not using aspnetcore you probably need to also include this NuGet package: Microsoft.Extensions.Configuration.Binder