Skip to content

Instantly share code, notes, and snippets.

@danielDevelops

danielDevelops/Config.cs

Last active Aug 13, 2019
Embed
What would you like to do?
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

This comment has been minimized.

Copy link

@joeygreen joeygreen commented Aug 7, 2019

Approved.

@joeygreen

This comment has been minimized.

Copy link

@joeygreen joeygreen commented Aug 7, 2019

Joey Green Completed the Pull Request

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