簡體   English   中英

.Net Core ConfigureAppConfiguration 添加額外的資源覆蓋環境特定設置

[英].Net Core ConfigureAppConfiguration adding additional sources overriding environment specific settings

在具有通用主機的 .NET Core 2.1 應用程序中使用 IConfigurationBuilder 時,我配置了 4 個源; 但在 ConfigureAppConfiguration 的范圍之后有 6 個來源。

在某些時候,我已經加載的 2 個額外源被第二次添加,順序導致 appsettings.Environment.json 值被隱藏。 我還嘗試刪除 hostsettings.json 配置並驗證這不會影響這一點。 這是針對使用 WebjobsSDK 3.0 和 .Net Core 2.1 的 Azure Webjob

    var builder = new HostBuilder()
        .ConfigureHostConfiguration(configurationBuilder =>
        {
             //This is to do some basic host configuration and should only add 2 sources
         configurationBuilder.SetBasePath(Directory.GetCurrentDirectory());
                configurationBuilder.AddJsonFile("hostsettings.json", optional: true);
                configurationBuilder.AddEnvironmentVariables(prefix: "APPSETTING_ASPNETCORE_");
            })
            .ConfigureAppConfiguration((hostContext, configurationBuilder) =>
            {
                //at this point there are 0 sources in the sources
                IHostingEnvironment env = hostContext.HostingEnvironment;
                configurationBuilder.SetBasePath(Directory.GetCurrentDirectory());
                configurationBuilder.AddJsonFile("appSettings.json", optional: false, reloadOnChange: true)
                    .AddJsonFile($"appSettings.{env.EnvironmentName}.json", optional: true,
                        reloadOnChange: true);
                configurationBuilder.AddEnvironmentVariables(prefix: "APPSETTING_ASPNETCORE_");
               //at this point there are 4 sources
            })
            .ConfigureServices((hostContext, servicesCollection) =>
            {
                //now there are 6, 2 additional source that are duplicates
                servicesCollection.Configure<IConfiguration>(hostContext.Configuration);

})

我希望配置提供程序只有 4 個源,包括 ChainedConfigSource,我已經設置好了。 但是添加了 2 個額外的源,它們是 appsettings.json 和我在加載特定於環境的 appsettings.environment.json 之前聲明的環境變量的副本。

現在,當將其注入到類中時,最后添加的 appsettings.json 設置將通過 appsettings.environment.json 返回

但是添加了 2 個額外的源,它們是appsettings.json和環境變量的副本

我在使用HostBuilder的 Azure WebJob 中遇到了類似的問題,並注意到這兩個源已附加到配置源列表的末尾。 這產生了不良結果:來自appsettings.Production.json的開發設置覆蓋了來自appsettings.json的生產設置。

這些額外的來源似乎是ConfigureWebJobs在此處添加的。

修復是重新排序HostBuilder調用鏈,以便對ConfigureAppConfiguration的調用在對ConfigureWebJobs的調用之前進行。 這兩個額外的源仍然存在,但由於它們現在位於配置源列表的開頭,而不是末尾,因此它們沒有不良影響。

可以重新排序builder.Sources以滿足您的需求。 例如,這里有一個擴展方法,您可以使用它在最后一個文件之后添加一個新的 JSON 文件,而不是在最后:

public static class ConfigurationBuilderExtensions
{
  public static IConfigurationBuilder AddJsonFileAfterLastJsonFile(this IConfigurationBuilder builder, string path, bool optional, bool reloadOnChange)
  {
    var jsonFileSource = new JsonConfigurationSource
    {
      FileProvider = null,
      Path = path,
      Optional = optional,
      ReloadOnChange = reloadOnChange
    };
    jsonFileSource.ResolveFileProvider();
    var lastJsonFileSource = builder.Sources.LastOrDefault(s => s is JsonConfigurationSource);
    var indexOfLastJsonFileSource = builder.Sources.IndexOf(lastJsonFileSource);
    builder.Sources.Insert(indexOfLastJsonFileSource == -1
      ? builder.Sources.Count
      : indexOfLastJsonFileSource + 1, jsonFileSource);
    return builder;
  }
}

然后你可以像這樣使用它:

.ConfigureAppConfiguration((hostingContext, config) =>
{
    config.AddJsonFileAfterLastJsonFile(
      "appsettings.Custom.json",
      optional: true,
      reloadOnChange: false);
})

您可以根據需要對其進行調整,並將其插入到您需要的任何位置。

閱讀 Hostbuilder.cs 類的源代碼,您將看到在 AddHostingConfiguration 中添加的配置被添加到 ApplicationConfiguration 中。

讓我告訴你,你可以在https://github.com/aspnet/AspNetCore/blob/1c3fa82908fe2cb773626b6613843213286a482b/src/Microsoft.Extensions.Hosting/HostBuilder.cs找到源代碼

構建調用將首先創建 HostingConfiguration,然后是 AppConfiguration。

這是構建 HostingConfiguration 的代碼

    private void BuildHostConfiguration()
    {
        var configBuilder = new ConfigurationBuilder();
        foreach (var buildAction in _configureHostConfigActions)
        {
            buildAction(configBuilder);
        }
        _hostConfiguration = configBuilder.Build();
     }

現在在 BuildAppConfiguration 中,您將看到 HostingConfiguration 被添加到 AppConfiguration 之上

    private void BuildAppConfiguration()
    {
        var configBuilder = new ConfigurationBuilder();
        //Here _hostConfiguration gets added ontop
        configBuilder.AddConfiguration(_hostConfiguration);
        foreach (var buildAction in _configureAppConfigActions)
        {
            buildAction(_hostBuilderContext, configBuilder);
        }
        _appConfiguration = configBuilder.Build();
        _hostBuilderContext.Configuration = _appConfiguration;
    }

現在構建函數是私有的,無法從構建器中重置/清除源代碼。

如果您不想實現自己的 HostBuilder 版本,我建議您不要將 Host 設置與 Appsettings 分開

因此,根據文檔,WebHostBuilder 會為您加載 appSettings.json 和 appSettings.env.json 文件。 但它也沒有說明 HostBuilder 也這樣做,我認為這是由於缺乏文檔,我無法確定源代碼的來源。

為解決此問題,我更改了配置文件的設置方式。 以前,我在 appSettings.json 文件和 appSettings.env.json 文件中都有連接字符串。 所以我遇到了最后添加的配置文件替換基本配置文件中的值的問題。 我現在已將基於環境的設置僅移動到每個環境的配置文件中,並且僅將對所有環境全局的設置保留在基本配置文件中。

.NET 框架配置轉換設置的舊習慣似乎很難改掉。 我無法確定是否應將從多個提供程序聲明的 IConfiguration 中的相同鍵更改為最后加載的提供程序,我認為一些文檔涵蓋了這一點並確認了這一點,但現在我找不到它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM