Azure 应用程序配置到强类型配置对象

标签 azure asp.net-core .net-core configuration azure-app-configuration

我一直在玩弄 Azure App Configuration .

这是一个示例配置:

var environmentVariable = Environment.GetEnvironmentVariable("AppConfigurationConnectionString");
var config =
    new ConfigurationBuilder()
        .AddAzureAppConfiguration(options =>
        {
            options.Connect(environmentVariable)
                .ConfigureKeyVault(kv =>
                {
                    kv.SetCredential(new DefaultAzureCredential());
                });
        })
        .Build();

services.AddSingleton<IConfiguration>(config);

接下来,我可以注入(inject) IConfiguration实例到我的服务并使用 _config["settingName"]访问配置设置。这一切都运行良好,而且非常好。

我不知道该怎么做的一件事是将相关设置组映射到强类型对象(也就是说,无需手动完成所有操作,我可以这样做,但是...希望有更好的方法)。

在传统的 ASP.NET Core 配置中,我可以按如下方式对相关设置进行分组(即在 appsettings.json 中)

{
    "test": {
        "key1": "value1",
        "key2": "value2"
    }
}

使用 IOptions 模式如下:

services.Configure<Test>(config.GetSection("test"));

这允许我注入(inject)强类型 IOptions<Test>实例进入我的类(class)。 IMO 这比一个大的平面索引器好一点,我在其中使用 _config["key1"]获取配置设置。

Azure 应用程序配置是否有一种方法可以让我自动配置可以注入(inject)到我的类中的强类型配置对象?

TIA

最佳答案

.NET Core 在将 appsettings.json 中的对象导入 IConfiguration 时将其展平。例如,您的 test 对象将成为 IConfiguration 中的以下两个键

_config["测试:key1"]

_config["测试:key2"]

这意味着您可以通过以这种扁平化方式存储设置,使用 Azure 应用程序配置准确地完成您想要的任务。 Azure 门户中的 Azure 应用程序配置 UI 有一个导入实用程序,允许您导入 appsettings.json 文件,它会为您执行此导入操作。

以下是正在使用的导入实用程序的示例: enter image description here

enter image description here

在 Azure 应用程序配置中拥有扁平化对象后,您拥有的确切代码将起作用。

关于Azure 应用程序配置到强类型配置对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61244046/

相关文章:

ios - 将图像上传到 Azure 并获取其 URL

asp.net - .NET Core 2.0 cookie 身份验证 - 不重定向

c# - 在 Linux 服务器上远程调试 ASP.NET Core

c# - 使用 Azure Kinect DK 将 In32Rect 坐标转换为 Span<BGRA>

c# - 寻找.net核心的容器的stdout和stderr

c# - CloudBlob.DownloadToStream 返回 null

sql - SQL 用户在 Azure 中导出 bacpac 所需的最低角色是什么?

python - 如何将数据框中的字符串转换为浮点值

asp.net-core - 将visual studio升级到16.10.0后拒绝加载_framework/aspnetcore-browser-refresh.js

c# - 尝试将参数传递给新的 EventHandler