How to Read a Configuration Section from XML in a Database?

后端 未结 5 1681
失恋的感觉
失恋的感觉 2021-02-01 04:01

I have a Config class like this:

public class MyConfig : ConfigurationSection
{
        [ConfigurationProperty(\"MyProperty\", IsRequired = true)]
        public         


        
5条回答
  •  轮回少年
    2021-02-01 04:42

    Here is how I usually do it: just add these members to the MyConfig class:

        public class MyConfig : ConfigurationSection
        {
            private static MyConfig _current;
            public static MyConfig Current
            {
                get
                {
                    if (_current == null)
                    {
                        switch(ConfigurationStorageType) // where do you want read config from?
                        {
                            case ConfigFile: // from .config file
                                _current = ConfigurationManager.GetSection("MySectionName") as MyConfig;
                                break;
    
                            case ConfigDb: // from database
                            default:
                                using (Stream stream = GetMyStreamFromDb())
                                {
                                    using (XmlTextReader reader = new XmlTextReader(stream))
                                    {
                                        _current = Get(reader);
                                    }
                                }
                                break;
    
    
                        }
                    }
                    return _current;
                }
            }
    
            public static MyConfig Get(XmlReader reader)
            {
                if (reader == null)
                    throw new ArgumentNullException("reader");
    
                MyConfig section = new MyConfig();
                section.DeserializeSection(reader);
                return section;
            }
        }
    

    This way, you have nothing to change in the MyConfig class, but you still need to change the way your customers access it with this kind of code:

    string myProp = MyConfig.Current.MyProperty;
    

提交回复
热议问题