- Introduction
- Defining a Custom XML Section
- Implementing a Custom IConfigurationSectionHandler
- Adding the configSection to the Configuration File
- Food for Thought
Adding the configSection to the Configuration File
Recall that I mentioned that section handlers are loaded dynamically and the methods are invoked using Reflection. This works because .NET supports dynamic assembly loading and already knows about the IConfigurationSectionHandler interface; that is, it knows to invoke Create. .NET doesn't need to know what you named your class. All .NET needs to do is use Reflection to load the assembly, reflect the class, create an instance, inquire and discover the IConfigurationSectionHandler, and know that this means there is a Create method. Voilà!
This implies that you still have to tell .NET which assembly contains your section handler, the namespace containing the class that implements the handler, and the section to which the handler applies. All of these elements are put together in a complete XML .config file in Listing 4.
Listing 4 A complete .config file containing the <configSections> tag indicating the precise assembly and name of our handler and the custom section.
<?xml version="1.0" encoding="utf-8" ?> <configuration> <configSections> <section name="playerDefaultOptions" type="ConfigSectionHandler.MySectionHandler, ConfigSectionHandler" /> </configSections> <playerDefaultOptions> <player name="Player 1"></player> <options> <hints value="On"></hints> <noSurrender value="Off"></noSurrender> <playHintsOnly value="Off"></playHintsOnly> </options> </playerDefaultOptions> </configuration>
In <configSections> we define the custom XML section we want our handler to read. The type attribute defines the namespace and class, using the namespace.class notation followed by a comma and the assembly name. In our example, the assembly is ConfigSectionHandler. An easy way to make sure that the section handler is accessible is to place it in the \bin folder where your application resides. You can also strongly name the assembly and register it in the Global Assembly Cache (GAC).