Encapsulating your settings in a constant manner is a great idea.
What I do is create a settings class either one static global one or multiple instance classes which I'll then manage with dependency injection. Then I load all the settings from configuration into that class on start up.
I've also written a little library that makes use of reflection to make this even easier.
Once my settings are in my config file
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="Domain" value="example.com" />
<add key="PagingSize" value="30" />
<add key="Invalid.C#.Identifier" value="test" />
</appSettings>
</configuration>
I make a static or instance class depending on my needs. For simple applications with only a few settings one static class is fine.
private static class Settings
{
public string Domain { get; set; }
public int PagingSize { get; set; }
[Named("Invalid.C#.Identifier")]
public string ICID { get; set; }
}
Then using my library call either Inflate.Static
or Inflate.Instance
and the cool thing is I can use any key value source.
using Fire.Configuration;
Inflate.Static( typeof(Settings), x => ConfigurationManager.AppSettings[x] );
All the code for this is in GitHub at https://github.com/Enexure/Enexure.Fire.Configuration
There is even a nuget package:
PM> Install-Package Enexure.Fire.Configuration
Code for reference:
using System;
using System.Linq;
using System.Reflection;
using Fire.Extensions;
namespace Fire.Configuration
{
public static class Inflate
{
public static void Static( Type type, Func<string, string> dictionary )
{
Fill( null, type, dictionary );
}
public static void Instance( object instance, Func<string, string> dictionary )
{
Fill( instance, instance.GetType(), dictionary );
}
private static void Fill( object instance, Type type, Func<string, string> dictionary )
{
PropertyInfo[] properties;
if (instance == null) {
// Static
properties = type.GetProperties( BindingFlags.Public | BindingFlags.Static | BindingFlags.DeclaredOnly );
} else {
// Instance
properties = type.GetProperties( BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly );
}
// Get app settings and convert
foreach (PropertyInfo property in properties) {
var attributes = property.GetCustomAttributes( true );
if (!attributes.Any( x => x is Ignore )) {
var named = attributes.FirstOrDefault( x => x is Named ) as Named;
var value = dictionary((named != null)? named.Name : property.Name);
object result;
if (ExtendConversion.ConvertTo(value, property.PropertyType, out result)) {
property.SetValue( instance, result, null );
}
}
}
}
}
}
WebConfigurationManager.AppSettings
because it's much easer to change later