簡體   English   中英

在.Net 5.0中配置服務時如何使用配置數據?

[英]How to use configuration data when configuring services in .Net 5.0?

我正在嘗試使用已配置的自定義配置類來配置另一個服務。 配置從本地設置和 Azure AppConfiguration 存儲中獲取數據。 這是我的啟動代碼:

public void ConfigureServices(IServiceCollection services)
{
    services.AddAzureAppConfiguration();
    services.Configure<CustomConfig>(Configuration);

    services.AddTransient<ISomeService, SomeService>((serviceProvider) => 
        {
            CustomConfig config = serviceProvider.GetRequiredService<IOptions<CustomConfig>>().Value;
            return new SomeService(config);
        });
    //--------------------------------------------------------------------
    services.AddRazorPages();
    services.AddControllers();
}

但是當 SomeService 被實例化時,我的自定義配置對象不包含應該來自 Azure AppConfig 的數據。 它只有來自 appsettings.json 的數據。 出了什么問題,我能在這里做什么?

所以簡短的回答是:它確實有效。 我懷疑有一些愚蠢的錯誤,情況確實如此(注釋了幾行代碼,因此沒有從 Azure 檢索數據 - 真丟人)。

感謝@pinkfloydx33 保證該模式應該有效。

如果有人想知道綁定根配置值 - 它也可以。 在我的例子中,appsettings.json 包含我需要連接到 Azure AppConfig 存儲的根值(主要和次要端點、刷新間隔和用於關鍵標簽的環境名稱)和一些與外部服務相對應的部分:數據庫、AAD B2C從 Azure AppConfig 中檢索到的等。 所以我的自定義 class 有根值和一些像這樣的嵌套類:

public class CustomConfig : ConfigRoot
{
    // These root values come from appsettings.json or environment variables in Azure
    [IsRequired]
    public string Env { get; set; }

    [IsRequired, Regex("RegexAppConfigEndpoint")]
    public Uri AppConfigEndpointPrimary { get; set; }

    [IsRequired, Regex("RegexAppConfigEndpoint")]
    public Uri AppConfigEndpointSecondary { get; set; }

    public int AppConfigRefreshTimeoutMinutes { get; set; } = 30;

    // And these sections come from the Azure AppConfig(s) from the above
    public ConfigSectionDb Db { get; set; } = new ConfigSectionDb();

    public ConfigSectionB2c B2c { get; set; } = new ConfigSectionB2c();
    
    // Some other sections here...
}

這里 ConfigSection<...> 類又包含其他子類。 所以我在這里有一個層次結構。 這里的 ConfigRoot 是一個抽象的 class 提供 Validate 方法。

它有效:這個services.Configure<CustomConfig>(Configuration); 部分獲取所有數據 - 來自所有已配置提供程序的根和部分。 就我而言,它是兩個 Azure AppConfigs、appsettings.json、環境變量。

暫無
暫無

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

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