AppSettings와 applicationSettings의 장단점 (.NET app.config / Web.config)
.NET Windows Forms 응용 프로그램을 개발할 때 App.config
구성 값을 저장하기 위해 해당 태그 중에서 선택할 수 있습니다. 어느 것이 더 낫습니까?
<configuration>
<!-- Choice 1 -->
<appSettings>
<add key="RequestTimeoutInMilliseconds" value="10000"/>
</appSettings>
<!-- Choice 2 -->
<configSections>
<sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c5612342342" >
<section name="Project1.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c5612342342" requirePermission="false" />
</sectionGroup>
</configSections>
<applicationSettings>
<Project1.Properties.Settings>
<setting name="TABLEA" serializeAs="String">
<value>TABLEA</value>
</setting>
</Project1.Properties.Settings>
</applicationSettings>
</configuration>
기본 사항 <appSettings>
은 다루기가 더 쉽습니다. <add key="...." value="..." />
항목을 두드리면 완료됩니다.
단점은 형식 검사가 없다는 것입니다. 예를 들어 구성하려는 숫자가 실제로 숫자라고 가정 할 수는 없습니다. 누군가가 해당 설정에 문자열을 넣을 수 ConfigurationManager["(key)"]
있습니다. 당신이 무엇을 다루고 있는지 알기 위해.
또한 <appSettings>
앱의 많은 부분이 거기에 물건을 넣기 시작하면 시간이 지남에 따라 다소 복잡하고 지저분해질 수 있습니다 (이전 windows.ini 파일을 기억하십니까? :-)).
가능하다면 .NET 2.0을 사용하면 자신의 구성 섹션을 사용하는 것이 좋습니다. 실제로는 매우 쉬워졌습니다.
- a) 코드에서 구성 설정을 정의하고 형식이 안전하고 확인되도록합니다.
- b) 귀하는 깨끗하게 분리 할 수 있습니다 당신의 다른 사람의에서 설정. 구성 코드도 재사용 할 수 있습니다!
CodeProject의 .NET 2.0 구성 시스템을 이해하기위한 일련의 유용한 기사가 있습니다.
추천! Jon Rista는 .NET 2.0의 구성 시스템을 잘 설명했습니다.
응용 프로그램 설정은 디자이너 (일반적으로 기본적으로 Settings.settings 파일이 있음)에서 제어 할 수 있으므로 수정하기 쉬우 며 강력한 형식의 속성처럼 보이는 Settings 클래스를 통해 프로그래밍 방식으로 액세스 할 수 있습니다. 롤백을위한 기본 설정뿐만 아니라 응용 프로그램 및 사용자 수준 설정을 가질 수도 있습니다.
이것은 .NET 2.0 이상에서 사용할 수 있으며 다른 방법으로 사용하지 않습니다 (알 수있는 한).
자세한 내용은 msdn.microsoft.com/en-us/library/k4s6c3a0.aspx를 참조하십시오.
기본 xml 태그를 사용하지만 정적 구성 클래스의 설정을 래핑하는 패턴을 사용하고 있습니다. 따라서 DIY App.Settings.
이 방법으로 수행하면 다음이 가능합니다.
- 환경에 따라 다른 구성 값 세트 사용 (dev, test, prod)
- 각 설정에 적절한 기본값을 제공
- 값을 정의하고 인스턴스화하는 방법 제어
설정하기가 지루하지만 성능이 좋으며 키 이름에 대한 참조를 숨기고 강력하게 입력됩니다. 이러한 종류의 패턴은 응용 프로그램에 의해 변경되지 않은 구성에 적합하지만 변경 사항을 지원할 수도 있습니다.
구성 :
<add key="machineName" value="Prod" />
<add key="anotherMachineName" value="Test" />
<add key="EnvTypeDefault" value="Dev" />
<add key="RootURLProd" value="http://domain.com/app/" />
<add key="RootURLTest" value="http://test.domain.com/app/" />
<add key="RootURLDev" value="http://localhost/app/" />
<add key="HumanReadableEnvTypeProd" value="" />
<add key="HumanReadableEnvTypeTest" value="Test Mode" />
<add key="HumanReadableEnvTypeDev" value="Development Mode" />
구성 클래스 :
using System;
using System.Collections.Generic;
using System.Web;
using WebConfig = System.Web.Configuration.WebConfigurationManager;
public static class Config
{
#region Properties
public static string EnvironmentType { get; private set; }
public static Uri RootURL { get; private set; }
public static string HumanReadableEnvType { get; private set; }
#endregion
#region CTOR
/// <summary>
/// Initializes all settings when the app spins up
/// </summary>
static Config()
{
// Init all settings here to prevent repeated NameValueCollection lookups
// Can increase performance on high volume apps
EnvironmentType =
WebConfig.AppSettings[System.Environment.MachineName] ??
"Dev";
RootURL =
new Uri(WebConfig.AppSettings["RootURL" + EnvironmentType]);
HumanReadableEnvType =
WebConfig.AppSettings["HumanReadableEnvType" + Config.EnvironmentType] ??
string.Empty;
}
#endregion
}
이해하기 위해 전문가 및 단점 의 설정을 app.config
, 난 당신이 둘의 기술적 인 세부 사항을 조사하는 것이 좋습니다. 처리 할 소스 코드를 찾을 수있는 링크를 포함 시켰으며 아래에 기술적 인 세부 정보가 설명되어 있습니다.
내가 잠시 내가 그들과 함께 일 때 인식 것을 요약하자 ( 참고 : 동일은에 적용 할 수 web.config
있는 웹 사이트 / 웹 응용 프로그램의 파일) :
applicationSettings
(click above to view source code and technical details)
Pros
They allow to store typed data, including object types (via
serializeAs
property)They have a user and application scope, allowing to store default values
They are supported in Visual Studio's configuration section
Long strings and/or data with special characters are very well supported (for example, embedded JSON strings containing double quotes)
Cons
User settings are stored in a different place in the user profile (with a cryptic path), can be difficult to clean up
Application scope settings are read-only during runtime of the application (only user scope settings can be changed during runtime)
Read / Write methods code built by Visual Studio's settings designer, not directly provided by 3rd party tools (see link above for a workaround solution)
AppSettings
(click above to view source code and technical details)
Pros
Are "light-weight", i.e. easy to handle
Read and write access during runtime of the application
They can be edited easily by Administrators in the
Internet Information Services (IIS) Manager
(Features View -> Application Settings, note that the name of the icon is misleading since it can only handle AppSettings and not ApplicationSettings)
Cons
Support only string data; string length and special characters are limited
They don't have a user scope
They don't support default values
Are not directly supported in Visual Studio's configuration section
I like working with the simpler version for storing and accessing single values.
<appSettings>
<add key="MyConfigKey" value="true"/>
</appSettings>
I wrote a utility class to access values in a typesafe way that allows for default values. If defaults are not provided, then helpful exception messages are given.
You can see/download the class here:
'development' 카테고리의 다른 글
Java 프로그램 콘솔 출력을 여러 파일로 어떻게 리디렉션 할 수 있습니까? (0) | 2020.06.03 |
---|---|
NumPy에서 배열을 정규화하는 방법은 무엇입니까? (0) | 2020.06.03 |
HTML 스크립트 태그 : 유형 또는 언어 (또는 둘 다 생략)? (0) | 2020.06.03 |
소켓의 연결 시간과 읽기 시간 초과의 차이점은 무엇입니까? (0) | 2020.06.03 |
권한을 부여하려고 시도하는 동안 사용자 'root'@ 'localhost'에 대한 액세스가 거부되었습니다. (0) | 2020.06.03 |