ConfigurationManager.GetSection Skips Duplicates

2019-09-04 08:03发布

问题:

Long story short, the .Net ConfigurationManager.GetSection method skips duplicates, and I'm looking for a best practice for handling this. I have a config file that includes something like this:

   <views>
     <view name="BusinessUnitsView" Desc="desc1"/>
     <view name="BusinessUnitsView" Desc="desc2"/>
   </views>

I have a graph of objects the config loads onto where collections derive from our derived version of ConfigurationElementCollection. The views collection in the graph only has one item in it after loading the above--my understanding is that this is simply the way the ConfigurationManager handled duplicates. The last item with the same key wins.

I could throw an exception on a duplicate being found by using BaseAdd(element, true). However, if possible I'd like to get the object completely loaded WITH duplicates, as the config gets read in a service layer, and I'd like to detect and deal with the problem on the consuming side of the service.

Do I have any options for modifying the way adds to the collection work?

回答1:

You will need to create your own ConfigurationSection. See here or here (the second link's method has been deprecated, but it may still shed some light)

This allows you to represent internal configuration variables as collections, and set properties like DefaultValue and IsRequired.



回答2:

Maybe you only want to iterate over a list but the main idea of the config is that you can do

var view = SomeConfigClass["BusinessUnitsView"];

That only allows one answer.