-
Notifications
You must be signed in to change notification settings - Fork 0
Sections Grouped
Below is an example of a Configuration Section in an app.config.
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<sectionGroup name="TestingGroup">
<section name="TestGroupSection" type="ConfigurationAssist.Tests.Configuration.TestGroupSection, ConfigurationAssist.Tests"/>
</sectionGroup>
</configSections>
<TestingGroup>
<TestProperties
testPropertyOne="one"
testPropertyTwo="two"
testPropertyThree="three"/>
</TestingGroup>
</configuration>As you can see here we have a configuration section called TestGroupSection. The type is the fully namespaced reference to the configuration class to be used along with the assembly that class belongs too. It also belongs to a section group called TestingGroup
To set up this class we merely add the ConfigurationAssist reference to that project, then create the class as shown below:
using System.Configuration;
using ConfigurationAssist.CustomAttributes;
namespace ConfigurationAssist.Tests.Configuration
{
//Add in the group as the second property
[ConfigurationSectionItem("TestGroupSection", "TestingGroup")]
public class TestGroupSection: ConfigurationSection
{
[ConfigurationProperty("testPropertyOne")]
public string TestPropertyOne { get; set; }
[ConfigurationProperty("testPropertyTwo")]
public string TestPropertyTwo { get; set; }
[ConfigurationProperty("testPropertyThree")]
public string TestPropertyThree { get; set; }
}
}There are three things to keep in mind here:
- The class attribute is found in our project ConfigurationAssist.CustomAttributes.ConfigurationSectionItem
- The class MUST inherit from System.Configurations.ConfigurationSection
- The properties must have the System.Configurations.ConfigurationProperty set referencing the attribute names from the config.
That's it, the class is configured, now all we need to do is query it out. There is an Interface for this for if you want to use injection. In the example below though, I will just strongly reference a new instance of it.
To retrieve your configuration settings:
var configAssistant = new ConfigurationAssist.ConfigurationAssist();
//If you have the ConfigurationSectionItem applied you can just call it like this
var testConfiguration = configAssistant.ExtractSettings<TestGroupSection>();
var value1 = testConfiguration.TestPropertyOne;
var value2 = testConfiguration.TestPropertyTwo;
var value3 = testConfiguration.TestPropertyThree;