using Microsoft.Extensions.Configuration; using System.Collections.Generic; using System.Linq; using EasyDevCore.Common; namespace EasyDevCore.Configuration { /// /// Auto substitute value from variableSection into section with value have data contains {@KeyName} /// /// public class SubstitutingConfigurationProvider : ConfigurationProvider { private readonly IConfigurationRoot _configurationRoot; private readonly string _variablesSection; private Dictionary _variables = null; /// /// Initializes a new instance of the class. /// /// The configuration root. /// The variables section. public SubstitutingConfigurationProvider(IConfigurationRoot configurationRoot, string variablesSection) { _configurationRoot = configurationRoot; _variablesSection = variablesSection; } /// /// Attempts to find a value with the given key, returns true if one is found, false otherwise. /// /// The key to lookup. /// The value found at key if one is found. /// True if key has a value, false otherwise. public override bool TryGet(string key, out string value) { try { foreach (var provider in _configurationRoot.Providers.Reverse()) { if (provider != this) { if (provider.TryGet(key, out value)) { value = SubstitutePlaceholders(value); return true; } } } } catch { } value = null; return false; } /// /// Sets a value for a given key. /// /// The configuration key to set. /// The value to set. public override void Set(string key, string value) { foreach (var provider in _configurationRoot.Providers) { if (provider != this) { provider.Set(key, value); } } } /// /// Loads (or reloads) the data for this provider. /// public override void Load() { if(_variables != null) { _variables.Clear(); } else { _variables = new(); } _configurationRoot.GetSection(_variablesSection).GetChildren().ForEach(kp => _variables.Add(kp.Key, kp.Value ?? string.Empty)); } private string SubstitutePlaceholders(string value) { if (value == null || !value.Contains("{@")) return value; foreach (var varriableName in _variables) { value = value.Replace($"{{@{varriableName.Key}}}", varriableName.Value); if(!value.Contains("{@")) { break; } } return value; } } }