I'm wondering how the ConfigurationManager.AppSettings[Key]
works.
Does it read from the physical file each time I need a key? If so, should I be reading all the app settings of my web.config in a cache and then read from it?
Or does ASP.NET or IIS load the web.config file only once at application startup?
How do I verify whether the physical file is accessed by each read? If I change the web.config, IIS restarts my application, so I can't verify it that way.
Best Answer
It gets cached, on first access of a property, so it does not read from the physical file each time you ask for a value. This is why it is necessary to restart an Windows app (or Refresh the config) to get the latest value, and why an ASP.Net app automatically restarts when you edit web.config. Why ASP.Net is hard wired to restart is discussed in the references in the answer How to prevent an ASP.NET application restarting when the web.config is modified.
We can verify this using ILSpy and looking at the internals of System.Configuration:
At first, this does indeed look like it will get the section every time. Looking at GetSection:
The critical line here is the
PrepareConfigSystem()
method; this initializes an instance of theIInternalConfigSystem
field held by the ConfigurationManager - the concrete type isClientConfigurationSystem
As part of this load, an instance of the Configuration class is instantiated. This class is effectively an object representation of the config file, and appears to be held by the ClientConfigurationSystem's ClientConfigurationHost property in a static field - hence it is cached.
You could test this empirically by doing the following (in a Windows Form or WPF app):
ConfigurationManager.RefreshSection("appSettings")
In fact, I could have saved myself some time if I'd just read the comment on the RefreshSection method :-)