Concatenating .NET Core Configuration

Viewed 1312

Is there an easy way to concatenate configuration to avoid redundancy?

  "Directories": {
    "Root": "my\\root\\folder",
    "Log": "{Root}\\Log",
    "Data": "{Root}\\Data" 
  }

Instead of writing the full path of each directory, I can pass {Root} as a variable. This way, users just need to update 1 configuration line instead of all 3.

When I call Configuration["Directories:Log"], it returns as my\\root\\folder\\Log. Same thing with Data and other possible combinations. Basically if possible, I want to use other configuration as a variable inside the configuration file (appsettings.json).

1 Answers

Create a class to represent your settings and then methods that would do what you want, e.g. the below. Can do it in a .NET Core console app too doesn't have to be ASP.NET Core.

    public class YourSettings
    {
        public string Root { get; set; }
        public string Log { get; set; }
        public string Data { get; set; }

        public string LogPath => Log.Replace("{Root}", Root);
        public string DataPath => Data.Replace("{Root}", Root);
    }

Then register it:

    public IConfiguration Configuration { get; }

    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public void ConfigureServices(IServiceCollection services)
    {
       ...
       // Configure Options using Microsoft.Extensions.Options.ConfigurationExtensions
        services.Configure<YourSettings>(Configuration.GetSection(nameof(YourSettings))); // for your specific example just pass in the string "Directories" since you don't have a section called "YourSettings" - obviously just update the class to encompass whatever settings you want it to
        services.AddSingleton(Configuration); //for DI
       ...
    }

Then use it:

    private readonly YourSettings _settings;
    public YourController(IOptions<YourSettings> settings)
    {
        _spDataRepo = spDataRepo;
        _settings = settings.Value;
        DoStuffWithSettings();
    }

    public void DoStuffWithSettings()
    {
        Debug.Print($"Hey the logs are here: {_settings.LogPath}");
    }
Related