When we need to extract some settings from the external environment during system development, we need to use the. NET configuration file. For example, if the IOC container used in my framework needs to be flexibly selected, I need to extract the IOC container settings to the configuration file for configuration. There are several implementation methods.
1. Use deleettings
This is the simplest user setting that can be set and read.
String objContainer = ConfigurationManager. deleetiner ["objectContainer"];
Simple, practical, but not elegant.
2. Implement your own configuration Node
Public class ObjectContainerElement {public string Provider {get; set;} public string IocModule {get; set ;}}
Public class AgileFRConfigurationHandler: IConfigurationSectionHandler {public object Create (object parent, object configContext, XmlNode section) {var node = section. ChildNodes [0]; if (node. Name! = "ObjectContainer") throw new ConfigurationErrorsException ("Unrecognized configuration items", node); var config = new ObjectContainerElement (); foreach (XmlAttribute attr in node. attributes) {switch (attr. name) {case "provider": config. provider = attr. value; break; case "iocModule": config. iocModule = attr. value; break; default: throw new ConfigurationErrorsException ("Unrecognized configuration attributes", attr) ;}} return config ;}
// Use var config = ConfigurationManager. GetSection ("agileFRConfiguration") as ObjectContainerElement;
This method seems a little embarrassing, but it is too troublesome.
Method 2:
Inherits the ConfigurationSection class and works with the ConfigurationProperty feature to implement
Public class ObjectContainerElement: ConfigurationElement {[ConfigurationProperty ("provider", IsRequired = true)] public string Provider {get {return (string) this ["provider"];} set {this ["provider"] = (object) value ;}} [ConfigurationProperty ("iocModule", IsRequired = false)] public string IocModule {get {return (string) this ["iocModule"];} set {this ["iocModule"] = (object) value ;}}} /// <summary> /// configuration processing class /// </summary> public class AgileFRConfigurationHandler: ConfigurationSection {[ConfigurationProperty ("objectContainer", IsRequired = true)] public ObjectContainerElement ObjectContainer {get {return (ObjectContainerElement) this ["objectContainer"] ;}set {this ["objectContainer"] = (object) value ;}}}
// Use
var configurationHandler = (AgileFRConfigurationHandler)ConfigurationManager.GetSection("agileFRConfiguration");var objectContainer=configurationHandler.ObjectContainer;
This method is simple and elegant, and I like it.
3. Settings. settings
I don't like this method very much. It will generate the Class corresponding to the configuration file by itself. No more.