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

后端 未结 5 1621
失恋的感觉
失恋的感觉 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:47

    This is a hard problem. You could have a config file with some deliberately incorrect XML, override OnDeserializeUnrecognizedElement in your ConfigurationSection and then effectively bypass the file to ConfigurationSection mapping (essentially set your properties manually) - some refactoring would be needed, but you can still expose the same properties etc. It is a bit WTF, but possibly workable.

    I essentially describe how to do this with LINQ to XML in this blog post. In all of my code now I don't have classes that rely on ConfigurationSection, I use the technique described in my blog post to bypass that and return POCOs through an interface. This has made my code more unit testable, as I can easily use a stub for the interface.

    I can also easily move my configuration into a DB should I wish to do so- I just create a new class that implements my configuration interface and switch it in my IoC configuration. Microsoft didn't design the configuration system to be flexible, so you have to take that into consideration when using it in your own code.

    The only other way I can think of is to write the DB config out to a file and then read it in, but that is also weird!

提交回复
热议问题