Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use a dynamic settings.Blah instead of AppSettings["blah"]?

Tags:

c#

dynamic

c#-4.0

I get how to use dynamic in C# 4.0, however, I'm not sure how to take something and make it dynamic-able (my technical term).

For example, instead of ConfigurationManager.AppSettings["blah"], how can I make a wrapper of sorts that will let me just use it like a dynamic: settings.Blah ?

like image 228
Brandon Avatar asked Feb 05 '11 01:02

Brandon


2 Answers

You still need an entry point. However, from there the possibilities are quite flexible. This is an example idea to demonstrate how powerful dynamic dispatch can be:

public abstract class MyBaseClass
{
    public dynamic Settings
    {
        get { return _settings; }
    }

    private SettingsProxy _settings = new SettingsProxy();

    private class SettingsProxy : DynamicObject
    {
        public override bool TryGetMember(GetMemberBinder binder, out object result)
        {
            var setting = ConfigurationManager.AppSettings[binder.Name];
            if(setting != null)
            {
                result = setting.ToString();
                return true;
            }
            result = null;
            return false;
        }
    }
}
like image 54
Rex M Avatar answered Sep 21 '22 06:09

Rex M


New version with generics !!

public static  class WebConfiguration<T>
{
    public static dynamic Get {
        get { return _settings; }
    }

    static readonly SettingsProxy _settings = new SettingsProxy ();

    class SettingsProxy : DynamicObject
    {
        public override bool TryGetMember (GetMemberBinder binder, out object result)
        {
            var setting = ConfigurationManager.AppSettings [binder.Name];
            if (setting != null) {
                result = Convert.ChangeType (setting, typeof(T));
                return true;
            }
            result = null;
            return false;
        }
    }
}

Usage

WebConfiguration<int>.Get.UserNameLength
like image 20
ngonzalezromero Avatar answered Sep 24 '22 06:09

ngonzalezromero