Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Configuration binding doesn't work

I have the following settings:

{
  "AppSettings": {
    "ConnectionString": "mongodb://localhost:27017",
    "Database": "local",
    "ValidOrigins": [ "http://localhost:61229" ]
  },
  "Logging": {
    "IncludeScopes": false,
    "Debug": {
      "LogLevel": {
        "Default": "Warning"
      }
    },
    "Console": {
      "LogLevel": {
        "Default": "Warning"
      }
    }
  }
}

I do the binding:

    services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));

I have the following settings file:


    public class AppSettings
    {
        public string ConnectionString = "";
        public string Database = "";

        public List<string> ValidOrigins { get; set; }
    }

Doing the binding:

    AppSettings settings = new AppSettings();
    Configuration.GetSection("AppSettings").Bind(settings);

settings.ValidOrigins is OK, but ConnectionString and Database are both null. What am I doing wrong?

like image 332
gyozo kudor Avatar asked Sep 26 '17 12:09

gyozo kudor


2 Answers

The binder will only bind properties and not fields. Try using properties instead of fields for ConnectionString and Database.

public string ConnectionString { get; set; }

public string Database { get; set; }
like image 109
Henk Mollema Avatar answered Oct 23 '22 16:10

Henk Mollema


Also make sure that your properties aren't defined as auto-properties by accident:

// ❌ WRONG

public class Configuration {
   public string Database { get; }
}


// ✅ CORRECT

public class Configuration {
   public string Database { get; set; }    // <----- Property must have a public setter
}
like image 30
silkfire Avatar answered Oct 23 '22 14:10

silkfire