Skip to content

Instantly share code, notes, and snippets.

@jmarnold
Created June 6, 2011 14:53
Show Gist options
  • Save jmarnold/1010392 to your computer and use it in GitHub Desktop.
Save jmarnold/1010392 to your computer and use it in GitHub Desktop.
Configurable Configuration
public class ApplicationSetting : ISiteContextualEntity
{
public string Key { get; set; }
public string Value { get; set; }
public int SiteId { get; set; }
public Site Site { get; set; }
}
public class ApplicationSettingsProvider : ISettingsProvider
{
private readonly IServiceLocator _locator;
private readonly IObjectResolver _resolver;
public ApplicationSettingsProvider(IServiceLocator locator, IObjectResolver resolver)
{
_locator = locator;
_resolver = resolver;
}
public T SettingsFor<T>() where T : class, new()
{
return (T) SettingsFor(typeof (T));
}
public object SettingsFor(Type settingsType)
{
IBindingContext context = new BindingContext(_locator.GetInstance<ApplicationSettingsRequestData>(),
_locator).PrefixWith(settingsType.Name);
BindResult result = _resolver.BindModel(settingsType, context);
result.AssertNoProblems(settingsType);
return result.Value;
}
}
public class ApplicationSettingsRequestData : IRequestData
{
private readonly ISettingsCache _cache;
public ApplicationSettingsRequestData(ISettingsCache cache)
{
_cache = cache;
}
public object Value(string key)
{
object value = null;
Value(key, v => value = v);
return value;
}
public bool Value(string key, Action<object> callback)
{
var setting = _cache.Get(key);
if(setting == null)
{
return false;
}
callback(setting.Value);
return true;
}
public bool HasAnyValuePrefixedWith(string key)
{
return _cache.Contains(s => s.Key.StartsWith(key));
}
}
public interface ISettingsCache
{
ApplicationSetting Get(string key);
void Fill(string key, string value);
bool Has(string key);
bool Contains(Func<ApplicationSetting, bool> predicate);
void Clear();
}
public class NotificationSettings : IApplicationSettings
{
public string Subject { get; set; }
public string FromAddress { get; set;
}
public interface IAppConfigSettings { }
public interface IApplicationSettings { }
public class SettingsRegistrationConvention : IRegistrationConvention
{
public void Process(Type type, Registry registry)
{
if (!typeof(IApplicationSettings).IsAssignableFrom(type))
{
return;
}
registry
.For(type)
.Use(ctx => ctx.GetInstance<ApplicationSettingsProvider>().SettingsFor(type));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment