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;
}
}
}
}