Last active
August 13, 2019 19:55
-
-
Save danielDevelops/68dbe842acb54c977e02ac3ed8be472f to your computer and use it in GitHub Desktop.
Simple AppConfig class that supports caching of the data from the app.config or web.config
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Configuration; | |
using System.Collections.Concurrent; | |
namespace Config | |
{ | |
public static class AppConfig | |
{ | |
private static readonly AppConfigValues _config = new AppConfigValues(); | |
public static string MyAppConfigStringValue | |
=> _config.GetValue<string>("AppConfigStringKey"); | |
public static int MyAppConfigIntValue | |
=> _config.GetValue<int>("AppConfigIntKey", 777); | |
public static string GetTrimmedStringValue | |
=> _config.GetValue<string>("AppConfigStringKeyTrimmedValue",string.Empty, t => t.TrimEnd('/')); | |
private class AppConfigValues | |
{ | |
readonly ConcurrentDictionary<string, dynamic> _configValues = new ConcurrentDictionary<string, dynamic>(); | |
public T GetValue<T>(string field, T defaultValue = default, params Func<T,T>[] additionalExecutionOptions) | |
{ | |
if (_configValues.ContainsKey(field)) | |
{ | |
_configValues.TryGetValue(field, out var val); | |
return val; | |
} | |
var fieldValue = ConfigurationManager.AppSettings[field]; | |
T value; | |
if (string.IsNullOrWhiteSpace(fieldValue)) | |
value = defaultValue; | |
else | |
value = (T)Convert.ChangeType(ConfigurationManager.AppSettings[field], typeof(T)); | |
foreach (var item in additionalExecutionOptions) | |
{ | |
value = item(value); | |
} | |
_configValues.TryAdd(field, value); | |
return value; | |
} | |
public T2 GetConvertedValue<T, T2>(string field, Func<T, T2> convertMethod = null, T2 defaultValue = default) | |
{ | |
var convertedKey = $"{field}{typeof(T2)}"; | |
if (_configValues.ContainsKey(convertedKey)) | |
{ | |
_configValues.TryGetValue(field, out var val); | |
return val; | |
} | |
var fieldValue = ConfigurationManager.AppSettings[field]; | |
T2 value; | |
if (string.IsNullOrEmpty(fieldValue)) | |
value = defaultValue; | |
else | |
{ | |
var originalValue = (T)Convert.ChangeType(ConfigurationManager.AppSettings[field], typeof(T)); | |
value = convertMethod(originalValue); | |
} | |
_configValues.TryAdd(convertedKey, value); | |
return value; | |
} | |
} | |
} | |
} |
Joey Green Completed the Pull Request
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Approved.