-
Notifications
You must be signed in to change notification settings - Fork 0
Section Types and Strategies Explained
When working with configuration sections .Net offers multiple ways of setting the underlying type. I'm going to explain the main implementations and how to use ConfigAssist to extract those settings.
One of the more common types is the NameValueSectionHandler. This simply lets us work with name value pairs similar to how AppSettings works. In the code backend this binds to a NameValueCollection object. Here is an example of how to work with this type of section using ConfigAssist.
Configuration below, note the type specified, and the fact that we don't specify the assembly. We can if we want, but its not necessary most of the time. Note however that the assembly is System.
<configuration>
<configSections>
<section name="ValueKeySectionConfiguration" type="System.Configuration.NameValueSectionHandler"/>
</configSections>
<ValueKeySectionConfiguration>
<add key="Name" value="MyConfigSection" />
<add key="MaxValue" value="1000000000" />
</ValueKeySectionConfiguration>
</configuration>Next we layout our Configuration Class. I'm going to do this in the simplest format by laying out the name and parameter names (case) identical to the configuration. Using NameValueSectionHandler we don't need to inherit our class from ConfigurationSection
public class ValueKeySectionConfiguration
{
public string Name { get; set; }
public long MaxValue { get; set; }
}Nice and simple. Next we implement our extraction strategy to retrieve the settings.
var configAssist = new ConfigAssist();
var configuration = configAssist.ExtractSettings<ValueKeySectionConfiguration>(new NameValueHandlerSectionExtractionStrategy());
//you can now read the values anyway you want. I'm just going to show they are typed.
string name = configuration.Name;
long maxValue = configuration.MaxValue;