aspnet / MicrosoftConfigurationBuilders

Microsoft.Configuration.Builders
MIT License
118 stars 61 forks source link

SectionHandler for NameValueSectionHandler #200

Closed bgilbert6 closed 1 year ago

bgilbert6 commented 2 years ago

I have a custom section that uses NameValueSectionHandler, this is provided by Microsoft. It does not inherit ConfigurationSection, so I cannot implement a SectionHandler. How can these cases be handled without using Expand or Token mode?

...
   <section name="customSection" type="System.Configuration.NameValueSectionHandler" />
...

<customSection configBuilders="???">
      <add key="key" value="value" />
</customSection >
StephenMolloy commented 1 year ago

The short answer here is that these builders will not work with sections based on IConfigurationSectionHandler.

The slightly longer answer is that IConfigurationSectionHandler has been a deprecated model since the ConfigurationSection paradigm was introduced way back in .Net 2.0. The internals of .Net still read the raw Xml when creating these sections, so if you were to write/extend* a config builder and leverage ProcessRawXml, you can get a chance to handle these sections there. This is what Expand mode in the pre-3.0 version of these builders did.

But since these IConfigurationSectionHandlers don't produce ConfigurationSections, the internals of .Net can't pass the section through the ProcessConfigurationSection API. So these config builders won't even see them. This is just a limitation of the framework, and there's not much we can do to work around it here.

For NameValueSectionHandler specifically, afaik it parses the same xml format as AppSettingsSection which also produces a NameValueCollection in the end. I don't know your exact scenario, but you might be able to do an in-place replacement of the deprecated section handler with AppSettingsSection and have things "just work."

* - Note that the ProcessRawXml/Expand technique was specifically removed from these builders in 3.0 for reasons. It is technically possible to extend these builders and bring it back, but it is not recommended. A fresh approach with a custom config builder that uses ProcessRawXml and is not entangled with all the extra trappings of this project would be the way to go if you must work on an IConfigurationSectionHandler section.