开发者

How to get 2 different sections from web.config using one base ConfigurationSection class?

开发者 https://www.devze.com 2023-04-04 23:18 出处:网络
I need to get data from viewModelSettings section in web.config <vmSettings namespace=\"Site.Web.ViewModels\" assembly=\"Site.Web\"/>

I need to get data from viewModelSettings section in web.config

<vmSettings namespace="Site.Web.ViewModels" assembly="Site.Web"/>

and to be able to get namespace like this VM.Settings.Namespace VM2.Settings.Namespace

I created the following class, so I could use it like VM.Settings.Namespace

public class VM : ConfigurationSection
    {
        privat开发者_JAVA百科e static VM _settings = ConfigurationManager.GetSection("vmSettings") as VM;

        public static VM Settings
        {
            get { return _settings; }
        }  

   [ConfigurationProperty("namespace", IsRequired = true)]
        public string Namespace
        {
            get
            {                
                return (string)base["namespace"];
            }
        }
        [ConfigurationProperty("assembly", IsRequired = true)]
        public string Assembly
        {
            get
            {
                return (string)base["assembly"];
            }
        }        
    }

Now, I have another section(vmSettings2) the same as the above one but with different name <vmSettings2 namespace="Site2.Web.ViewModels" assembly="Site2.Web"/>

I didn't want to write another ConfigurationSection class but use the above one(but it should get vmSettings2 section) and use it like VM2.Settings.Namespace. How could I implement this? Maybe inherit from VM class, but how to override the section name?


Could you not convert your VM class into an abstract base class?

Then you could derive two classes from that called vmSettings1 and vmSettings2 which would simply use the methods defined in the base class?

You could possibly use VM as an interface but then you'd be forced to implement each method for each class which is possibly the type of thing you're hoping to avoid here.


Try this:

    public class VM : ConfigurationSection
    {

        public static VM GetSection(string section)
        {
            return ConfigurationManager.GetSection(section) as VM;
        }  

        [ConfigurationProperty("namespace", IsRequired = true)]
        public string Namespace
        {
            get
            {                
                return (string)base["namespace"];
            }
        }
        [ConfigurationProperty("assembly", IsRequired = true)]
        public string Assembly
        {
            get
            {
                return (string)base["assembly"];
            }
        }        
    }
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号