Simple wrapper around .NET appSettings.
<?xml version="1.0" encoding="utf-8" ?> | |
<configuration> | |
<startup> | |
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" /> | |
</startup> | |
<appSettings> | |
<add key="environment-type" value="Local" /> | |
<!--<add key="environment-log-minimum-level" value="Debug" />--> | |
<add key="auth0-client-id" value="abc123abc" /> | |
<add key="auth0-client-secret" value="123abc123abc" /> | |
<add key="auth0-domain" value="abc123.auth0.com" /> | |
<add key="auth0-database-connection-name" value="ABC123" /> | |
<add key="auth0-token-expiration-seconds" value="3600" /> | |
</appSettings> | |
</configuration> |
using System; | |
using System.Configuration; | |
using System.Diagnostics; | |
using System.Text.RegularExpressions; | |
using Castle.Components.DictionaryAdapter; | |
using Serilog.Events; | |
namespace StronglyTypedAppSettings | |
{ | |
internal class Program | |
{ | |
private static void Main(string[] args) | |
{ | |
var factory = new DictionaryAdapterFactory(); | |
var environment = factory.GetAdapter<IEnvironment>(ConfigurationManager.AppSettings); | |
var auth0 = factory.GetAdapter<IAuth0>(ConfigurationManager.AppSettings); | |
Debug.Assert(environment.Type == EnvironmentType.Local); | |
Debug.Assert(auth0.TokenExpirationSeconds == 3600); | |
} | |
} | |
[AppSettingWrapper] | |
public interface IEnvironment | |
{ | |
EnvironmentType Type { get; } | |
LogEventLevel LogMinimumLevel { get; } | |
} | |
[AppSettingWrapper] | |
public interface IAuth0 | |
{ | |
string ClientId { get; } | |
string ClientSecret { get; } | |
string Domain { get; } | |
string DatabaseConnectionName { get; } | |
int TokenExpirationSeconds { get; } | |
} | |
public enum EnvironmentType | |
{ | |
Undefined, | |
Local, | |
Test, | |
Uat, | |
Production | |
} | |
public class AppSettingWrapperAttribute : DictionaryBehaviorAttribute, IDictionaryKeyBuilder, | |
IPropertyDescriptorInitializer, IDictionaryPropertyGetter | |
{ | |
private readonly Regex converter = new Regex("([A-Z])", RegexOptions.Compiled); | |
public string GetKey(IDictionaryAdapter dictionaryAdapter, string key, PropertyDescriptor property) | |
{ | |
var name = dictionaryAdapter.Meta.Type.Name.Remove(0, 1) + key; | |
var adjustedKey = converter.Replace(name, "-$1").Trim('-'); | |
return adjustedKey; | |
} | |
public object GetPropertyValue(IDictionaryAdapter dictionaryAdapter, string key, object storedValue, | |
PropertyDescriptor property, bool ifExists) | |
{ | |
if (storedValue != null) return storedValue; | |
throw new InvalidOperationException(string.Format("App setting '{0}' not found!", key.ToLowerInvariant())); | |
} | |
public void Initialize(PropertyDescriptor propertyDescriptor, object[] behaviors) | |
{ | |
propertyDescriptor.Fetch = true; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment