.NET 中的設定

.NET 中的設定是使用一或多個設定提供者來執行的。 設定提供者會使用各種設定來源從機碼值組中讀取設定資料:

  • 設定檔案,如 appsettings.json
  • 環境變數
  • Azure Key Vault
  • Azure 應用程式組態
  • 命令列引數
  • 自訂提供者 (已安裝或已建立)
  • 目錄檔案
  • 記憶體內部 .NET 物件
  • 協力廠商提供者

注意

如需設定 .NET 執行階段的相關資訊,請參閱 .NET 執行階段組態設定

概念和抽象概念

給定一或多個設定來源,IConfiguration 類型為設定資料提供一個統一的視圖。 設定是唯讀的,而且設定模式的設計無法用程式設計方式寫入。 IConfiguration 介面是所有設定來源的單一表示法,如下圖所示:

The `IConfiguration` interface is a single representation of all the configuration sources.

設定主控台應用程式

根據預設,使用 dotnet new 命令範本或 Visual Studio 建立的 .NET 主控台應用程式不會公開設定功能。 若要在新的 .NET 主控台應用程式中新增設定,請在 Microsoft.Extensions.Configuration新增套件參考。 此套件是 .NET 應用程式中組態的基礎。 它提供 ConfigurationBuilder 和相關的型別。

using Microsoft.Extensions.Configuration;

var configuration = new ConfigurationBuilder()
    .AddInMemoryCollection(new Dictionary<string, string?>()
    {
        ["SomeKey"] = "SomeValue"
    })
    .Build();

Console.WriteLine(configuration["SomeKey"]);

// Outputs:
//   SomeValue

上述 程式碼:

  • 建立新的 ConfigurationBuilder 執行個體。
  • 將機碼/值組的記憶體內部集合新增至組態建立器。
  • 呼叫 Build() 方法來建立 IConfiguration 執行個體。
  • SomeKey 機碼的值寫入主控台。

雖然此範例使用記憶體內部組態,但有許多可用的組態提供者,並公開檔案型、環境變數、命令列引數和其他組態來源的功能。 如需詳細資訊,請參閱 .NET 中的組態提供者

替代裝載方法

通常,您的應用程式不只是讀取組態,還會執行更多作業。 它們可能會使用相依性插入、記錄和其他服務。 針對使用這些服務的應用程式,建議使用 .NET 泛型主機方法。 相反地,請考慮將套件參考新增至 Microsoft.Extensions.Hosting。 修改 Program.cs 檔案以符合下列程式碼:

using Microsoft.Extensions.Hosting;

using IHost host = Host.CreateApplicationBuilder(args).Build();

// Application code should start here.

await host.RunAsync();

Host.CreateApplicationBuilder(String[]) 方法會以下列順序為應用程式提供預設組態 (從最高到最低優先順序排列):

  1. 使用命令列設定提供者的命令列引數。
  2. 使用環境變數設定提供者的環境變數。
  3. 當應用程式在 Development 環境中執行時的應用程式祕密
  4. 使用 JSON 設定提供者appsettings.json
  5. 使用 JSON 設定提供者appsettings.Environmentjson。 例如,appsettings.Production.jsonappsettings.Development.json
  6. ChainedConfigurationProvider:將現有 IConfiguration 新增為來源。

新增設定提供者會覆寫先前的設定值。 例如,因為命令列設定提供者是最後新增的項目,所以它會覆寫所有來自其他提供者的值。 如果 SomeKeyappsettings.json 和環境中皆有設定,則會使用環境值,因為它是在 appsettings.json 之後新增的。

繫結

使用 .NET 設定抽象概念的主要優點之一,是它能夠將設定值繫結至 .NET 物件的執行個體。 例如,JSON 設定提供者可用來將 appsettings.json 檔案對應至 .NET 物件,並搭配相依性插入使用。 這會啟用選項模式,該模式會使用類別來提供相關設定群組的強型別存取。 .NET 設定提供各種抽象概念。 請考量下列介面:

這些抽象概念與其基礎設定提供者無關 (IConfigurationProvider)。 換句話說,您可以使用 IConfiguration 執行個體來存取多個提供者的任何設定值。

繫結器可以用不同的方法來處理設定值:

  • 基本類型的直接還原序列化 (使用內建轉換器)。
  • 針對複雜類型的 TypeConverter (如果類型中有複雜類型)。
  • 具有屬性之複雜類型的反映。

注意

繫結器有一些限制:

  • 如果屬性有私人 setter 或無法轉換類型,則該屬性會被忽略。
  • 沒有對應設定索引鍵的屬性會被忽略。

繫結階層

設定值可以包含階層式資料。 階層式物件會用設定索引鍵中的分隔符號 : 來表示。 若要存取設定值,請用 : 字元來分隔階層。 例如,請考慮下列設定值:

{
  "Parent": {
    "FavoriteNumber": 7,
    "Child": {
      "Name": "Example",
      "GrandChild": {
        "Age": 3
      }
    }
  }
}

下表代表上述 JSON 範例的索引鍵範例及其對應的值:

機碼
"Parent:FavoriteNumber" 7
"Parent:Child:Name" "Example"
"Parent:Child:GrandChild:Age" 3

基本範例

若要在不使用泛型主機方法的狀況下存取基本形式的設定值,請直接使用 ConfigurationBuilder 類型。

提示

System.Configuration.ConfigurationBuilder 類型與 Microsoft.Extensions.Configuration.ConfigurationBuilder 類型不同。 所有內容都僅適用於 Microsoft.Extensions.* NuGet 套件和命名空間。

請考慮以下 C# 專案:

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net8.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>true</ImplicitUsings>
  </PropertyGroup>

  <ItemGroup>
    <Content Include="appsettings.json">
      <CopyToOutputDirectory>Always</CopyToOutputDirectory>
    </Content>
  </ItemGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.Extensions.Configuration.Binder" Version="8.0.1" />
    <PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="8.0.0" />
    <PackageReference Include="Microsoft.Extensions.Configuration.EnvironmentVariables" Version="8.0.0" />
  </ItemGroup>

</Project>

上述專案檔參考了幾個設定 NuGet 套件:

請考慮一個 appsettings.json 檔案範例:

{
    "Settings": {
        "KeyOne": 1,
        "KeyTwo": true,
        "KeyThree": {
            "Message": "Oh, that's nice...",
            "SupportedVersions": {
                "v1": "1.0.0",
                "v3": "3.0.7"
            }
        },
        "IPAddressRange": [
            "46.36.198.121",
            "46.36.198.122",
            "46.36.198.123",
            "46.36.198.124",
            "46.36.198.125"
        ]
    }
}

假設使用此 JSON 檔案,以下是直接使用設定產生器的取用模式範例:

using Microsoft.Extensions.Configuration;

// Build a config object, using env vars and JSON providers.
IConfigurationRoot config = new ConfigurationBuilder()
    .AddJsonFile("appsettings.json")
    .AddEnvironmentVariables()
    .Build();

// Get values from the config given their key and their target type.
Settings? settings = config.GetRequiredSection("Settings").Get<Settings>();

// Write the values to the console.
Console.WriteLine($"KeyOne = {settings?.KeyOne}");
Console.WriteLine($"KeyTwo = {settings?.KeyTwo}");
Console.WriteLine($"KeyThree:Message = {settings?.KeyThree?.Message}");

// Application code which might rely on the config could start here.

// This will output the following:
//   KeyOne = 1
//   KeyTwo = True
//   KeyThree:Message = Oh, that's nice...

在上述 C# 程式碼中:

  • 具現化 ConfigurationBuilder
  • 新增 JSON 組態提供者所要辨識的 "appsettings.json" 檔案。
  • 將環境變數新增為由環境變數設定提供者辨識。
  • 使用 config 執行個體取得必要的 "Settings" 區段和對應的 Settings 執行個體。

物件 Settings 的形狀如下:

public sealed class Settings
{
    public required int KeyOne { get; set; }
    public required bool KeyTwo { get; set; }
    public required NestedSettings KeyThree { get; set; } = null!;
}
public sealed class NestedSettings
{
    public required string Message { get; set; } = null!;
}

裝載的基本範例

若要存取 IConfiguration 值,您可以再次使用 Microsoft.Extensions.Hosting NuGet 套件。 建立新的主控台應用程式,並將下列專案檔內容貼入其中:

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net8.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>true</ImplicitUsings>
  </PropertyGroup>

  <ItemGroup>
    <Content Include="appsettings.json">
      <CopyToOutputDirectory>Always</CopyToOutputDirectory>
    </Content>
  </ItemGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.Extensions.Hosting" Version="8.0.0" />
  </ItemGroup>

</Project>

上述專案檔會定義:

  • 應用程式是可執行檔。
  • 編譯專案時,會複製一個 appsettings.json 檔案到輸出目錄。
  • 已新增 Microsoft.Extensions.Hosting NuGet 套件參考。

使用下列內容在專案的根目錄新增 appsettings.json 檔案:

{
    "KeyOne": 1,
    "KeyTwo": true,
    "KeyThree": {
        "Message": "Thanks for checking this out!"
    }
}

使用下列 C# 程式碼取代 Program.cs 檔案中的內容:

using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

using IHost host = Host.CreateApplicationBuilder(args).Build();

// Ask the service provider for the configuration abstraction.
IConfiguration config = host.Services.GetRequiredService<IConfiguration>();

// Get values from the config given their key and their target type.
int keyOneValue = config.GetValue<int>("KeyOne");
bool keyTwoValue = config.GetValue<bool>("KeyTwo");
string? keyThreeNestedValue = config.GetValue<string>("KeyThree:Message");

// Write the values to the console.
Console.WriteLine($"KeyOne = {keyOneValue}");
Console.WriteLine($"KeyTwo = {keyTwoValue}");
Console.WriteLine($"KeyThree:Message = {keyThreeNestedValue}");

// Application code which might rely on the config could start here.

await host.RunAsync();

// This will output the following:
//   KeyOne = 1
//   KeyTwo = True
//   KeyThree:Message = Thanks for checking this out!

當您執行此應用程式時,Host.CreateApplicationBuilder 會定義探索 JSON 設定並透過 IConfiguration 執行個體公開它的行為。 從 host 執行個體中,您可以向服務提供者要求 IConfiguration 執行個體,然後要求它提供值。

提示

用這種方式使用原始 IConfiguration 執行個體雖然方便,但無法妥善調整。 當應用程式複雜度增加,且其對應的設定也變得更複雜時,建議您使用選項模式做為替代方案。

裝載和使用索引子 API 的基本範例

請考慮與上述範例相同的 appsettings.json 檔案內容:

{
    "SupportedVersions": {
        "v1": "1.0.0",
        "v3": "3.0.7"
    },
    "IPAddressRange": [
        "46.36.198.123",
        "46.36.198.124",
        "46.36.198.125"
    ]
}

使用下列 C# 程式碼取代 Program.cs 檔案中的內容:

using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

using IHost host = Host.CreateApplicationBuilder(args).Build();

// Ask the service provider for the configuration abstraction.
IConfiguration config = host.Services.GetRequiredService<IConfiguration>();

// Get values from the config given their key and their target type.
string? ipOne = config["IPAddressRange:0"];
string? ipTwo = config["IPAddressRange:1"];
string? ipThree = config["IPAddressRange:2"];
string? versionOne = config["SupportedVersions:v1"];
string? versionThree = config["SupportedVersions:v3"];

// Write the values to the console.
Console.WriteLine($"IPAddressRange:0 = {ipOne}");
Console.WriteLine($"IPAddressRange:1 = {ipTwo}");
Console.WriteLine($"IPAddressRange:2 = {ipThree}");
Console.WriteLine($"SupportedVersions:v1 = {versionOne}");
Console.WriteLine($"SupportedVersions:v3 = {versionThree}");

// Application code which might rely on the config could start here.

await host.RunAsync();

// This will output the following:
//     IPAddressRange:0 = 46.36.198.123
//     IPAddressRange:1 = 46.36.198.124
//     IPAddressRange:2 = 46.36.198.125
//     SupportedVersions:v1 = 1.0.0
//     SupportedVersions:v3 = 3.0.7

這些值可用索引子 API 來存取,其中每個索引鍵都是字串且值也是字串。 設定支援屬性、物件、陣列和字典。

設定提供者

下表顯示可供 .NET Core 應用程式使用的設定提供者。

提供者 從提供設定
Azure 應用程式設定提供者 Azure 應用程式組態
Azure Key Vault 組態提供者 Azure Key Vault
命令列設定提供者 命令列參數
自訂設定提供者 自訂來源
環境變數設定提供者 環境變數
檔案設定提供者 JSON、XML 和 INI 檔案
每個檔案機碼設定提供者 目錄檔案
記憶體設定提供者 記憶體內集合
應用程式秘密 (秘密管理員) 使用者設定檔目錄中的檔案

提示

新增設定提供者的順序是很重要的。 使用多個設定提供者,而且其中超過一個提供者指定相同的索引鍵時,會使用最後一個新增的項目。

如需各種設定提供者的詳細資訊,請參閱 .NET 中的設定提供者

另請參閱