Simple AppConfig

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Configuration;
  4. using System.Collections.Concurrent;
  5.  
  6. namespace Config
  7. {
  8. public static class AppConfig
  9. {
  10. private static readonly AppConfigValues _config = new AppConfigValues();
  11.  
  12. public static string MyAppConfigStringValue
  13. => _config.GetValue<string>("AppConfigStringKey");
  14.  
  15. public static int MyAppConfigIntValue
  16. => _config.GetValue<int>("AppConfigIntKey", 777);
  17.  
  18. public static string GetTrimmedStringValue
  19. => _config.GetValue<string>("AppConfigStringKeyTrimmedValue",string.Empty, t => t.TrimEnd('/'));
  20.  
  21.  
  22. private class AppConfigValues
  23. {
  24. readonly ConcurrentDictionary<string, dynamic> _configValues = new ConcurrentDictionary<string, dynamic>();
  25.  
  26. public T GetValue<T>(string field, T defaultValue = default, params Func<T,T>[] additionalExecutionOptions)
  27. {
  28. if (_configValues.ContainsKey(field))
  29. {
  30. _configValues.TryGetValue(field, out var val);
  31. return val;
  32. }
  33. var fieldValue = ConfigurationManager.AppSettings[field];
  34. T value;
  35. if (string.IsNullOrWhiteSpace(fieldValue))
  36. value = defaultValue;
  37. else
  38. value = (T)Convert.ChangeType(ConfigurationManager.AppSettings[field], typeof(T));
  39.  
  40. foreach (var item in additionalExecutionOptions)
  41. {
  42. value = item(value);
  43. }
  44.  
  45. _configValues.TryAdd(field, value);
  46. return value;
  47. }
  48. public T2 GetConvertedValue<T, T2>(string field, Func<T, T2> convertMethod = null, T2 defaultValue = default)
  49. {
  50. var convertedKey = $"{field}{typeof(T2)}";
  51. if (_configValues.ContainsKey(convertedKey))
  52. {
  53. _configValues.TryGetValue(field, out var val);
  54. return val;
  55. }
  56. var fieldValue = ConfigurationManager.AppSettings[field];
  57. T2 value;
  58. if (string.IsNullOrEmpty(fieldValue))
  59. value = defaultValue;
  60. else
  61. {
  62. var originalValue = (T)Convert.ChangeType(ConfigurationManager.AppSettings[field], typeof(T));
  63. value = convertMethod(originalValue);
  64. }
  65. _configValues.TryAdd(convertedKey, value);
  66. return value;
  67. }
  68. }
  69. }
  70. }