Programing

ConfigurationManager.AppSettings [Key]는 매번 web.config 파일에서 읽습니까?

lottogame 2020. 11. 12. 07:42
반응형

ConfigurationManager.AppSettings [Key]는 매번 web.config 파일에서 읽습니까?


ConfigurationManager.AppSettings [Key]가 어떻게 작동하는지 궁금합니다.

키가 필요할 때마다 실제 파일에서 읽습니까?

그렇다면 캐시에서 내 web.config의 모든 앱 설정을 읽어야합니까?

또는 ASP.NET 또는 IIS는 web.config 파일을 application_startup에서 한 번만로드합니다.

읽을 때마다 실제 파일에 액세스하는지 확인하는 방법은 무엇입니까?

web.config를 변경하면 IIS가 내 응용 프로그램을 다시 시작하므로 그렇게 확인할 수 없습니다.

감사,


속성에 처음 액세스 할 때 캐시되므로 값을 요청할 때마다 실제 파일에서 읽지 않습니다. 이것이 최신 값을 얻으려면 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()방법입니다. IInternalConfigSystemConfigurationManager가 보유한 필드 의 인스턴스를 초기화합니다 . 구체적인 유형은 다음과 같습니다.ClientConfigurationSystem

이로드의 일부로 Configuration 클래스 의 인스턴스 가 인스턴스화됩니다. 이 클래스는 사실상 구성 파일의 객체 표현이며 정적 필드에서 ClientConfigurationSystem의 ClientConfigurationHost 속성이 보유하는 것처럼 보이므로 캐시됩니다.

Windows Form 또는 WPF 앱에서 다음을 수행하여이를 경험적으로 테스트 할 수 있습니다.

  1. 앱 시작
  2. app.config의 값에 액세스
  3. app.config를 변경합니다.
  4. 새 값이 있는지 확인하십시오.
  5. 요구 ConfigurationManager.RefreshSection("appSettings")
  6. 새 값이 있는지 확인하십시오.

사실, 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>

간단한 대답은 '아니요'입니다. 항상 파일에서 읽는 것은 아닙니다. 파일이 변경되면 일부 사람들이 제안했듯이 IIS는 다시 시작하지만 항상 그런 것은 아닙니다! 캐시가 아닌 파일에서 최신 값을 읽고 있는지 확인하려면 다음과 같이 호출해야합니다.

ConfigurationManager.RefreshSection("appSettings");
string fromFile = ConfigurationManager.AppSettings.Get(key) ?? string.Empty;

그리고 내 코드에서 사용하는 예 :

/// ======================================================================================
/// <summary>
/// Refreshes the settings from disk and returns the specific setting so guarantees the
/// value is up to date at the expense of disk I/O.
/// </summary>
/// <param name="key">The setting key to return.</param>
/// <remarks>This method does involve disk I/O so should not be used in loops etc.</remarks>
/// <returns>The setting value or an empty string if not found.</returns>
/// ======================================================================================
private string RefreshFromDiskAndGetSetting(string key)
{
    // Always read from the disk to get the latest setting, this will add some overhead but
    // because this is done so infrequently it shouldn't cause any real performance issues
    ConfigurationManager.RefreshSection("appSettings");
    return GetCachedSetting(key);
}

/// ======================================================================================
/// <summary>
/// Retrieves the setting from cache so CANNOT guarantees the value is up to date but
/// does not involve disk I/O so can be called frequently.
/// </summary>
/// <param name="key">The setting key to return.</param>
/// <remarks>This method cannot guarantee the setting is up to date.</remarks>
/// <returns>The setting value or an empty string if not found.</returns>
/// ======================================================================================
private string GetCachedSetting(string key)
{
    return ConfigurationManager.AppSettings.Get(key) ?? string.Empty;
}

이를 통해 매번 최신 값을 가져 오는지 또는 응용 프로그램이 시작될 때 값이 변경 될 것으로 예상하지 않는지 여부를 매우 쉽게 선택할 수 있습니다 (코드를 읽을 때 확인).


var file =
            new FileInfo(@"\\MyConfigFilePath\Web.config");

        DateTime first  = file.LastAccessTime;

        string fn = ConfigurationManager.AppSettings["FirstName"];
        Thread.Sleep(2000);

        DateTime second = file.LastAccessTime;

        string sn = ConfigurationManager.AppSettings["Surname"];
        Thread.Sleep(2000);

        DateTime third = file.LastAccessTime;

모두 동일한 LastAccessTime을 표시하므로 시작시 캐시됩니다.

        string fn1 = ConfigurationManager.AppSettings["FirstName"];
        Thread.Sleep(2000);

        DateTime fourth = file.LastAccessTime;

참고URL : https://stackoverflow.com/questions/13357765/does-configurationmanager-appsettingskey-read-from-the-web-config-file-each-ti

반응형