구성 관리자를 수행합니다.매번 web.config 파일에서 AppSettings[Key]를 읽으시겠습니까?
어떻게 된 건지 궁금합니다.ConfigurationManager.AppSettings[Key]작동하다.
키가 필요할 때마다 실제 파일에서 읽습니까?그렇다면 캐시에서 web.config의 모든 앱 설정을 읽은 다음 읽어야 합니까?
아니면 ASP.NET 또는 IIS는 응용 프로그램을 시작할 때 web.config 파일을 한 번만 로드합니까?
각 읽기에서 물리적 파일에 액세스하는지 확인하려면 어떻게 해야 합니까?web.config를 변경하면 IIS가 응용 프로그램을 다시 시작하므로 확인할 수 없습니다.
속성에 처음 액세스할 때 캐시되므로 값을 요청할 때마다 실제 파일에서 읽지 않습니다.따라서 최신 값을 얻으려면 윈도우즈 앱을 다시 시작해야 하며(또는 구성 새로 고침), web.config를 편집할 때 ASP.Net 앱이 자동으로 다시 시작되는 이유입니다.ASP.Net을 다시 시작하는 데 유선 연결된 이유는 web.config가 수정될 때 ASP.NET 응용 프로그램이 다시 시작되는 것을 방지하는 방법에 대한 답변의 참조에서 설명합니다.
우리는 ILSpy를 사용하여 이를 확인할 수 있고 시스템의 내부를 확인할 수 있습니다.구성:
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()메소드; 이것은 인스턴스를 초기화합니다.IInternalConfigSystem구성 관리자가 보유한 필드 - 구체적인 유형은ClientConfigurationSystem
이 로드의 일부로 구성 클래스의 인스턴스가 인스턴스화됩니다.이 클래스는 효과적으로 구성 파일의 개체 표현이며 클라이언트 구성 시스템의 클라이언트 구성에 의해 유지되는 것으로 보입니다.정적 필드의 호스트 속성 - 캐시됩니다.
윈도우즈 Form 또는 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>
간단한 대답은 "아니오"입니다. 항상 파일에서 읽는 것은 아닙니다.일부에서 제안한 대로 파일이 변경되면 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;
모두 동일한 마지막 액세스 표시시작할 때 캐시된 시간입니다.
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
'programing' 카테고리의 다른 글
| JDK 1.6에서 Oracle SQL Developer를 실행하고 1.7에서 모든 것을 실행하려면 어떻게 해야 합니까? (0) | 2023.07.09 |
|---|---|
| 저는 Vue 3에서 Vuex에서 Pinia로 전환하고 있으며 현재 유닛 테스트에 실패하고 있습니다.사용자 지정 모의 작업을 만들 수 없는 것 같습니다. (0) | 2023.07.09 |
| 오류: mongodb를 연결하는 윈도우즈에서 유닉스 소켓을 지원하지 않습니다. (0) | 2023.07.09 |
| 콘다 명령을 찾을 수 없습니다. (0) | 2023.07.09 |
| 푸시 알림에서 앱이 시작/열렸는지 탐지 (0) | 2023.07.09 |