.NET Framework에서 Microsoft.Extensions.Configuration의 ConfigurationProvider 사용

12881 단어 dotnetaspdotnetaspnet
.NET Core는 .NET Framework에서 많이 변경되었으며 많은 새 라이브러리/API를 도입했습니다. 이러한 라이브러리 중 일부는 실제로 .NET Framework를 비롯한 여러 .NET 플랫폼을 지원하도록 빌드되었습니다. 따라서 여전히 .NET Framework를 사용하는 경우 이러한 새 라이브러리를 활용할 수도 있습니다.

dotnet/extensions를 예로 들면 다음과 같습니다.

.NET Extensions is an open-source, cross-platform set of APIs for commonly used programming patterns and utilities, such as dependency injection, logging, and app configuration. Most of the API in this project is meant to work on many .NET platforms, such as .NET Core, .NET Framework , Xamarin, and others. While commonly used in ASP.NET Core applications, these APIs are not coupled to the ASP.NET Core application model. They can be used in console apps, WinForms and WPF, and others.

Source: dotnet/extensions repository



이러한 라이브러리는 매우 유용하지만 그 외에도 많은 다른 오픈 소스 프로젝트에서 이와 동일한 라이브러리를 사용합니다. 예를 들어 Serilog은 오픈 소스 로깅 라이브러리이며 Serilog를 구성하는 한 가지 방법은 Microsoft.Extensions.Configuration 라이브러리를 사용하는 것입니다. 이 구성 라이브러리를 사용할 때 Microsoft.Extensions.Configuration 의 라이브 다시 로드 기능으로 인해 애플리케이션을 다시 시작하지 않고도 로거의 로그 수준을 변경할 수 있습니다. 이것은 .NET Framework에서 Serilog를 구성하는 일반적인 방법으로는 불가능합니다.

견본



스핀을 위해 Microsoft.Extensions.Configuration 라이브러리를 사용하려면 다음 단계를 따르십시오.
  • Visual Studio를 사용하여 .NET Framework 콘솔 앱 만들기
  • NuGet 패키지 관리자 콘솔을 사용하여 프로젝트에 다음 패키지를 추가합니다.

  • Install-Package Microsoft.Extensions.Configuration.Json -Version 3.1.8
    Install-Package Microsoft.Extensions.Configuration.CommandLine -Version 3.1.8
    Install-Package Microsoft.Extensions.Configuration.Binder -Version 3.1.8
    


    Json 패키지는 JSON 파일에 대한 지원을 구성으로 추가합니다. CommandLine 패키지는 string[] args를 구성으로 변환하는 데 도움이 됩니다. 바인더 패키지는 구성을 유형이 지정된 개체에 바인딩합니다.
  • myconfig.json라는 프로젝트의 루트에 json 파일을 만들고 다음 내용을 추가합니다.

  • {
      "name": "Best pizza",
      "toppings": [
        "Marinara sauce",
        "Cheese",
        "More cheese",
        "Pineapple",
        "More pineapple"
      ]
    }
    


  • Program.cs 파일 업데이트:

  • using Microsoft.Extensions.Configuration;
    using System;
    using System.Collections.Generic;
    using System.IO;
    
    class Program
    {
        static void Main(string[] args)
        {
            var configuration = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                // load in the json file as configuration
                .AddJsonFile(path: "myconfig.json", optional: false, reloadOnChange: true)
                // override configuration from the json file with commandline arguments
                .AddCommandLine(args)
                .Build();
        }
    }
    


    이제 configuration 개체를 사용하여 JSON 파일 및 명령줄 인수에서 데이터를 읽을 수 있습니다.
  • 구성을 수동으로 추출하는 대신 Bind 기능을 사용하여 구성 데이터를 유형이 지정된 개체에 바인딩할 수 있습니다. 바인딩 코드로 Program.cs 파일을 업데이트합니다.

  • using Microsoft.Extensions.Configuration;
    using System;
    using System.Collections.Generic;
    using System.IO;
    
    class Program
    {
        static void Main(string[] args)
        {
            var configuration = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                // load in the json file as configuration
                .AddJsonFile(path: "myconfig.json", optional: false, reloadOnChange: true)
                // override configuration from the json file with commandline arguments
                .AddCommandLine(args)
                .Build();
    
            var pizza = new Pizza();
            configuration.Bind(pizza);
    
            Console.WriteLine($"Pizza name: {pizza.Name}");
            Console.WriteLine($"Pizza toppings:");
            foreach (var topping in pizza.Toppings)
            {
                Console.WriteLine($"- {topping}");
            }
    
            Console.WriteLine("Press any enter to exit");
            Console.ReadLine();
        }
    }
    
    public class Pizza
    {
        public string Name { get; set; }
        public List<string> Toppings { get; set; }
    }
    


    구성을 바인딩하려면 먼저 새 유형의 클래스를 만들고 해당 클래스의 새 인스턴스를 만든 다음 configuration.Bind 에 전달해야 합니다.

    이 작은 프로그램의 출력은 다음과 같습니다.

    Pizza name: Best pizza
    Pizza toppings:
    - Marinara sauce
    - Cheese
    - More cheese
    - Pineapple
    - More pineapple
    Press any enter to exit
    


    명령줄 인수를 전달하여 구성을 수정할 수 있습니다.

    ./ConfigurationBuilderOnFramework.exe /toppings:4 "Mushrooms" /toppings:5 "Sausage"
    # Output:
    #   Pizza name: Best pizza
    #   Pizza toppings:
    #   - Marinara sauce
    #   - Cheese
    #   - More cheese
    #   - Pineapple
    #   - Mushrooms
    #   - Sausage
    #   Press any enter to exit
    


    JSON 및 명령줄 공급자 외에도 더 많은 공급자를 활용할 수 있습니다. NuGet.org에서 "Microsoft.Extensions.Configuration"을 검색하면 다음과 같은 더 많은 것을 찾을 수 있습니다.
  • Microsoft.Extensions.Configuration.EnvironmentVariables
  • Microsoft.Extensions.Configuration.UserSecrets
  • Microsoft.Extensions.Configuration.Ini
  • Microsoft.Extensions.Configuration.Xml
  • Microsoft.Extensions.Configuration.AzureKeyVault
  • Microsoft.Extensions.Configuration.KeyPerFile
  • Microsoft.Extensions.Configuration.AzureAppConfiguration

  • 요약



    많은 새로운 API/라이브러리/패키지가 .NET Core와 함께 도입되었지만 일부는 .NET Framework, Xamarin 등과 같은 다른 .NET 플랫폼과도 호환됩니다. 새로운 구성 API는 매우 강력하며 사용할 수 있습니다. .NET 프레임워크에서.

    좋은 웹페이지 즐겨찾기