DanSharpe
DanSharpe

Reputation: 71

dotnet core configuration binding not working

I am trying to bind a model from a custom configurationsource, but it wont bind the properties, my class is:

public class Secrets
{
    public string DbConnectionString { get; set; }
}

The configuration source returns the correct values, its serialized into a dictionary that has the following key value pair
https://i.sstatic.net/TB823.png

Code in my startup is this:

 var c = Configuration.GetSection("AWSSecrets").Get<Secrets>();

but DBConnectionString is always null, if i do:

var config = new Secrets();
        config.DbConnectionString = Configuration.GetValue<string>("AWSSecrets:dbConnectionString");

then it picks out the property, any idea why my property wont bind automatically?

Upvotes: 1

Views: 8911

Answers (2)

Amir
Amir

Reputation: 2052

If your appsettings is like below:

{
   "AWSSecrets":{
                  "DbConnectionString":""
                }
}

First inject your model in startup.

 services.Configure<Secrets>(Configuration.GetSection("AWSSecrets"));

And access it anywhere using the Ioptions.

 private readonly IOptions<Secrets> _secrets;
 public YourClassContructor(IOptions<Secrets> secrets)
 {
     _secrets=secrets;
     string conStr =_secrets.value.DbConnectionString;
 }     

Make sure your dependency are injected properly. And also you need to have Microsoft.Extensions.Options.ConfigurationExtensions which you can install from package manager.

Upvotes: 3

HariHaran
HariHaran

Reputation: 4199

Instead of Get you need to Bind it like this

var secrets = new Secrets();
Configuration.GetSection("AWSSecrets").Bind(secrets);

In order to access your DbConnectionString just do secrets.DbConnectionString.

You can also do this in your startup and inject in your constructor if you want.

services.Configure<Secrets>(Configuration.GetSection("AWSSecrets"));

Upvotes: 2

Related Questions