Search code examples
c#asp.net-core-3.1application-settings

Accessing top-level fields in AppSettings.json from injected configuration class


Say we have such AppSettings.json

{
  "Region": Europe,
  "WeirdService": {
    "JustField": "value"
  }
}

Registering WeirdService settings in separate, singleton class (or using options pattern) is fine, just:

service.AddSingleton(configuration.GetSection("WeirdService").Get<WeirdService>();

And at this point it's fine. I don't know however how to deal cleanly with this top-level properties like Region in my example.

I know I can just inject IConfiguration and use config.GetValue<string>("Region") or just access configuration directly, but I wonder if there is some clean, better way without hardcoding this stuff in services.

Edit

I forgot to mention. Team I'm currently working with uses .NET Core 3.1 as it's current LTS release.


Solution

  • I think the easiest way would be to just create a class for the toplevel keys. In your case you could create something like AppConfig with the single property Region. Then you just register it without getting a config section using the Configuration object, the Configure methods asks for a Configuration interface anyway and not a ConfigurationSection.

    AppConfig:

    public class AppConfig
    {
        public string? Region { get; set; }
    }
    

    Registration:

    public static IServiceCollection AddOptions(this IServiceCollection services, IConfiguration configuration)
    {
        return services.Configure<AppConfig>(configuration);
    }
    

    Usage:

    public class ExampleConsumer
    {
        public ExampleConsumer(IOptions<AppConfig> appConfig) {}
    }