.Net 5.0配置服务时如何使用配置数据?

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

我正在尝试使用已配置的自定义配置-class 来配置另一项服务。配置从本地设置和 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 存储的根值(主要和次要端点、刷新间隔和在关键标签中使用的环境名称)以及与外部服务对应的几个部分:数据库,从 Azure AppConfig 检索的 AAD B2C 等。 所以我的自定义 class 有根值和一些嵌套的 classes:

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<...> classes 依次包含其他子classes。所以我在这里有一个层次结构。这里的 ConfigRoot 是一个抽象 class 提供 Validate 方法。

它有效:这个 services.Configure<CustomConfig>(Configuration); 部分获取所有数据 - 来自所有已配置提供程序的根和部分。在我的例子中,它是两个 Azure AppConfigs,appsettings.json,环境变量。