プロパティへの最初のアクセス時にキャッシュされるため、値を要求するたびに物理ファイルから読み取ることはありません。これが、最新の値を取得するためにWindowsアプリを再起動する(または構成を更新する)必要がある理由であり、web.configを編集するとASP.Netアプリが自動的に再起動する理由です。ASP.Netを再起動するように配線されている理由については、web.configが変更されたときにASP.NETアプリケーションが再起動しないようにする方法のリファレンスで説明されています。
これは、 ILSpyを使用し、System.Configurationの内部を確認することで確認できます。
public static NameValueCollection AppSettings
{
get
{
object section = ConfigurationManager.GetSection("appSettings");
if (section == null || !(section is NameValueCollection))
{
throw new ConfigurationErrorsException(SR.GetString("Config_appsettings_declaration_invalid"));
}
return (NameValueCollection)section;
}
}
最初は、これは確かに毎回セクションを取得するように見えます。GetSectionを見てください:
public static object GetSection(string sectionName)
{
if (string.IsNullOrEmpty(sectionName))
{
return null;
}
ConfigurationManager.PrepareConfigSystem();
return ConfigurationManager.s_configSystem.GetSection(sectionName);
}
ここで重要なのはPrepareConfigSystem()
メソッドです。これにより、ConfigurationManagerが保持するフィールドのインスタンスが初期化されますIInternalConfigSystem
。具体的なタイプは次のとおりです。ClientConfigurationSystem
このロードの一部として、Configurationクラスのインスタンスがインスタンス化されます。このクラスは、事実上、構成ファイルのオブジェクト表現であり、静的フィールドのClientConfigurationSystemのClientConfigurationHostプロパティによって保持されているように見えます。したがって、キャッシュされます。
次の手順を実行することで、これを経験的にテストできます(WindowsフォームまたはWPFアプリで)。
- アプリを起動する
- app.configの値にアクセスします
- app.configに変更を加えます
- 新しい値が存在するかどうかを確認します
- 電話
ConfigurationManager.RefreshSection("appSettings")
- 新しい値が存在するかどうかを確認します。
実際、 RefreshSectionメソッドのコメントを読んだだけで、時間を節約できたはずです:-)
/// <summary>Refreshes the named section so the next time that it is retrieved it will be re-read from disk.</summary>
/// <param name="sectionName">The configuration section name or the configuration path and section name of the section to refresh.</param>