123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104 |
- using Microsoft.Extensions.Configuration;
- using System.Collections.Generic;
- using System.Linq;
- using EasyDevCore.Common;
- namespace EasyDevCore.Configuration
- {
- /// <summary>
- /// Auto substitute value from variableSection into section with value have data contains {@KeyName}
- /// </summary>
- /// <seealso cref="Microsoft.Extensions.Configuration.ConfigurationProvider" />
- public class SubstitutingConfigurationProvider : ConfigurationProvider
- {
- private readonly IConfigurationRoot _configurationRoot;
- private readonly string _variablesSection;
- private Dictionary<string, string> _variables = null;
- /// <summary>
- /// Initializes a new instance of the <see cref="SubstitutingConfigurationProvider"/> class.
- /// </summary>
- /// <param name="configurationRoot">The configuration root.</param>
- /// <param name="variablesSection">The variables section.</param>
- public SubstitutingConfigurationProvider(IConfigurationRoot configurationRoot, string variablesSection)
- {
- _configurationRoot = configurationRoot;
- _variablesSection = variablesSection;
- }
- /// <summary>
- /// Attempts to find a value with the given key, returns true if one is found, false otherwise.
- /// </summary>
- /// <param name="key">The key to lookup.</param>
- /// <param name="value">The value found at key if one is found.</param>
- /// <returns>True if key has a value, false otherwise.</returns>
- 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;
- }
- /// <summary>
- /// Sets a value for a given key.
- /// </summary>
- /// <param name="key">The configuration key to set.</param>
- /// <param name="value">The value to set.</param>
- public override void Set(string key, string value)
- {
- foreach (var provider in _configurationRoot.Providers)
- {
- if (provider != this)
- {
- provider.Set(key, value);
- }
- }
- }
- /// <summary>
- /// Loads (or reloads) the data for this provider.
- /// </summary>
- 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;
- }
- }
- }
|