Skip to content

Instantly share code, notes, and snippets.

@danielDevelops
Last active August 13, 2019 19:55
Show Gist options
  • Save danielDevelops/68dbe842acb54c977e02ac3ed8be472f to your computer and use it in GitHub Desktop.
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
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;
}
}
}
}
@joeygreen
Copy link

Approved.

@joeygreen
Copy link

Joey Green Completed the Pull Request

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment