Multiple ConfigurationElement types in ConfigurationElementCollection

I would like to have a configuration section, for example:

<mycollection> <add name="myelement" type="class, assembly" var1="value" var2="value" /> <add name="myelement2" type="class2, assembly" var1="value" var3="value" var4="value" /> </mycollection> 

The idea is that the actual ConfigurationElement created is determined by the type value and each element will have its own specific set of attributes.

Another option is that all elements are the same, but they load values ​​from another section of the configuration, for example:

 <mycollection> <add name="myelement" configuration="myothersection" /> <add name="myelement2" configuration="myothersection2" /> </mycollection> <myothersection type="class, assembly" var1="value" var2="value" /> 

This is easier to implement, but leads to a more detailed configuration file.

Is the first option related to the .NET configuration template, and secondly, is this possible?

+4
source share
2 answers

Yes it is possible! See this post for more details:

http://code.dblock.org/2009/02/18/nesting-multiple-configurationelement-types-in-a-configurationelementcollection.html

Along the same lines, here is a solution that allows you to read extremely flexible xml using IConfigurationSectionHandler: http://alt.pluralsight.com/wiki/default.aspx/Craig/XmlSerializerSectionHandler.html

+2
source

Something else you could do is override OnDeserializeUnrecognizedElement . Thus, you can create a ParametersConfigurationElement element as follows:

 <parameters> <string name="Patrick Huizinga" /> <string country="the Netherlands" /> <int currentScore="206" /> </parameters> 

OnDeserializeUnrecognizedElement runs an XmlReader in which you can learn about the attributes of a custom item. Using TypeConverter.ConvertFromInvariantString (you can get TypeConverter from TypeDescriptor.GetConverter ) you can even support types like DateTime and Uri, without any extra effort.

+3
source

Source: https://habr.com/ru/post/1286036/


All Articles