Advertisement
Guest User

Untitled

a guest
Jul 23rd, 2019
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.50 KB | None | 0 0
  1. [LayoutRenderer("connectionstrings")]
  2. public class ConnectionStringsLayoutRenderer : LayoutRenderer
  3. {
  4. private static IConfigurationRoot _configurationRoot;
  5.  
  6. internal IConfigurationRoot DefaultAppSettings
  7. {
  8. get => _configurationRoot;
  9. set => _configurationRoot = value;
  10. }
  11.  
  12. /// <summary>
  13. /// Global configuration. Used if it has set
  14. /// </summary>
  15. public static IConfiguration AppSettings { private get; set; }
  16.  
  17. ///<summary>
  18. /// The AppSetting name.
  19. ///</summary>
  20. [RequiredParameter]
  21. [DefaultParameter]
  22. public string Name { get; set; }
  23.  
  24. ///<summary>
  25. /// The default value to render if the AppSetting value is null.
  26. ///</summary>
  27. public string Default { get; set; }
  28.  
  29. public ConnectionStringsLayoutRenderer()
  30. {
  31.  
  32. if (AppSettings == null && DefaultAppSettings == null)
  33. {
  34. DefaultAppSettings = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory())
  35. .AddJsonFile("appsettings.json")
  36. .AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")}.json", optional: true).Build();
  37. }
  38. }
  39.  
  40. /// <summary>
  41. /// Renders the specified application setting or default value and appends it to the specified <see cref="StringBuilder" />.
  42. /// </summary>
  43. /// <param name="builder">The <see cref="StringBuilder"/> to append the rendered data to.</param>
  44. /// <param name="logEvent">Logging event.</param>
  45. protected override void Append(StringBuilder builder, LogEventInfo logEvent)
  46. {
  47. if (Name == null) return;
  48.  
  49. string value = AppSettingValue;
  50. if (value == null && Default != null)
  51. value = Default;
  52.  
  53. if (string.IsNullOrEmpty(value) == false)
  54. builder.Append(value);
  55. }
  56.  
  57. private bool _cachedAppSettingValue = false;
  58. private string _appSettingValue = null;
  59. private string AppSettingValue
  60. {
  61. get
  62. {
  63. Name = Name.Replace('.', ':');
  64. if (_cachedAppSettingValue == false)
  65. {
  66. _appSettingValue = AppSettings == null ? DefaultAppSettings.GetConnectionString(Name) : AppSettings[Name];
  67. _cachedAppSettingValue = true;
  68. }
  69. return _appSettingValue;
  70. }
  71. }
  72. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement