-2

我正在尝试使用已配置的自定义配置类来配置另一个服务。配置从本地设置和 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 的数据。出了什么问题,我能在这里做什么?

4

1 回答 1

0

所以简短的回答是:它确实有效。我怀疑有一些愚蠢的错误,而事实正是如此(注释了几行代码,因此没有从 Azure 中检索到数据——真让我感到羞耻)。

感谢@pinkfloydx33 保证该模式应该有效。

如果有人想知道绑定根配置值 - 它也可以。在我的例子中,appsettings.json 包含我需要连接到 Azure AppConfig 存储的根值(主要和次要端点、刷新间隔和用于键标签的环境名称)以及与外部服务相对应的几个部分:数据库、AAD B2C等从 Azure AppConfig 检索。所以我的自定义类有根值和一些像这样的嵌套类:

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 是一个提供 Validate 方法的抽象类。

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

于 2021-02-02T11:11:42.380 回答