Created
February 6, 2014 14:46
-
-
Save NikolajDL/8845534 to your computer and use it in GitHub Desktop.
A dynamic object to wrap WebConfigurationManager.AppSettings to access the settings "prettily". Great in combination with a custom ASP.NET MVC WebViewPage for easy access in views.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public abstract class MyWebViewPage<TModel> : WebViewPage<TModel> | |
{ | |
public dynamic Settings | |
{ | |
get { return SettingsHelper.Instance; } | |
} | |
} | |
public abstract class MyWebViewPage : WebViewPage | |
{ | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class SettingsHelper : DynamicObject | |
{ | |
private static dynamic instance = new SettingsH(); | |
private static object syncRoot = new object(); | |
private SettingsHelper() { } | |
public static dynamic Instance | |
{ | |
get { | |
if (instance == null) | |
{ | |
lock (syncRoot) | |
{ | |
if (instance == null) | |
instance = new SettingsHelper(); | |
} | |
} | |
return instance; | |
} | |
} | |
public override bool TryGetMember(GetMemberBinder binder, out object result) | |
{ | |
if (WebConfigurationManager.AppSettings.AllKeys.Contains(binder.Name)) | |
{ | |
result = WebConfigurationManager.AppSettings[binder.Name]; | |
return true; | |
} | |
result = null; | |
return false; | |
} | |
public override bool TrySetMember(SetMemberBinder binder, object value) | |
{ | |
var key = binder.Name; | |
if (WebConfigurationManager.AppSettings.AllKeys.Contains(key)) | |
WebConfigurationManager.AppSettings.Set(key, value.ToString()); | |
else | |
WebConfigurationManager.AppSettings.Add(key, value.ToString()); | |
return true; | |
} | |
public override string ToString() | |
{ | |
StringWriter message = new StringWriter(); | |
foreach (var item in WebConfigurationManager.AppSettings.AllKeys) | |
message.WriteLine("{0}:\t{1}", item, WebConfigurationManager.AppSettings[item]); | |
return message.ToString(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment