development

AppSettings와 applicationSettings의 장단점 (.NET app.config / Web.config)

big-blog 2020. 6. 3. 08:04
반응형

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 구성 시스템을 이해하기위한 일련의 유용한 기사가 있습니다.

  1. .NET 2.0 구성의 미스터리 해결

  2. .NET 2.0 구성의 미스터리 디코딩

  3. .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.

DotNetPearls 정적 구성 패턴

이 방법으로 수행하면 다음이 가능합니다.

  • 환경에 따라 다른 구성 값 세트 사용 (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:

http://www.drewnoakes.com/code/util/app-settings-util/

참고URL : https://stackoverflow.com/questions/460935/pros-and-cons-of-appsettings-vs-applicationsettings-net-app-config-web-confi

반응형