Reputation: 663
I have created a custom config section to store a list of of items. The config is as follows:
<configSections>
<section name="Items" type="namespace.Items, namespace"/>
</configSections>
<Items>
<Item name="Item1"/>
<Item name="Item2"/>
</Items>
I have also created my own configuration handler as follows:
public class ItemConfigurationHandler : IConfigurationSectionHandler
{
public ItemConfigurationHandler()
{
}
public object Create(object parent, object configContext, System.Xml.XmlNode section)
{
List<Item> items = new List<Item>();
System.Xml.XmlNodeList items = section.SelectNodes("Item");
foreach (XmlNode i in items)
{
Item item = new Item();
item.Name = i.Attributes["name"].InnerText;
items.Add(item);
}
return items;
}
}
This is currently working fine and I can retrieve a list of items from the config as follows:
List<Item> ts = (List<Item>)ConfigurationManager.GetSection("Items");
I am wondering however, is it possible to just retrieve a single item? For example, if I wanted the details of "Item1" only. I can successfully retrieve the list and then filter where name = "Item1" but this means loading all the XML which seems a bit much if only want one item from the list, especially as this list grows, i dont want to load 20 items if I only need one, or is this not much of an issue?
Upvotes: 2
Views: 957
Reputation: 5866
Is there a reason you need to store these items in the web.config
? The web.config
file, conceptually, is meant for configuration settings. If you plan to programatically read/write to this file, could you store the data in your own custom xml file and parse the data from there?
EDIT : Since your comment suggests you'd like to keep these items in the web.config, I don't believe it would be a major issue to retrieve the entire list and iterate through to find the necessary value. You could add values to the <appSettings>
tag and access them individually as well.
e.g.:
<appSettings>
<add key="item1" value="item1 value"/>
<add key="item2" value="item2 value"/>
. . .
<add key="item20" value="item20 value"/>
</appSettings>
Access it like so:
var item1Value = ConfigurationManager.AppSettings["item1"];
Though, if you're only reading this information I'm unclear as to why you're set on putting them in the configuration file to begin with. It might be easier just to define these variables within the code.
Upvotes: 2
Reputation: 31641
I would say it's not a big issue - loading 1 versus 20 you aren't going to see a blip on today's machines unless you have nested XML configurations.
ConfigurationManager also caches the values, so once you query the config section they remain in memory for subsequent requests. You can use ConfigurationManager.RefreshSection("Items")
to refresh the cache.
Upvotes: 2