Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Map appsettings.json to class

I'm trying to convert appsettings.json to C# class

I use Microsoft.Extensions.Configuration to read the configuration from appsettings.json

I write the following code using reflection but I'm looking for a better solution

foreach (var (key, value) in configuration.AsEnumerable())
{
    var property = Settings.GetType().GetProperty(key);
    if (property == null) continue;
    
    object obj = value;
    if (property.PropertyType.FullName == typeof(int).FullName)
        obj = int.Parse(value);
    if (property.PropertyType.FullName == typeof(long).FullName)
        obj = long.Parse(value);
    property.SetValue(Settings, obj);
}
like image 433
AliReza Beigy Avatar asked Jan 24 '23 12:01

AliReza Beigy


1 Answers

Build configuration from appsettings.json file:

var config = new ConfigurationBuilder()
            .AddJsonFile("appsettings.json", optional = false)
            .Build()

Then add Microsoft.Extensions.Configuration.Binder nuget package. And you will have extensions to bind configuration (or configuration section) to the existing or new object.

E.g. you have a settings class (btw by convention it's called options)

public class Settings
{
    public string Foo { get; set; }
    public int Bar { get; set; }
}

And appsettings.json

{
  "Foo": "Bob",
  "Bar": 42
}

To bind configuration to new object you can use Get<T>() extension method:

var settings = config.Get<Settings>();

To bind to existing object you can use Bind(obj):

var settings = new Settings();
config.Bind(settings);
like image 123
Sergey Berezovskiy Avatar answered Jan 27 '23 03:01

Sergey Berezovskiy