教程:在 .NET Core 应用中使用动态配置Tutorial: Use dynamic configuration in a .NET Core app

应用配置 .NET Core 客户端库支持按需更新一组配置设置,不需让应用程序重启。The App Configuration .NET Core client library supports updating a set of configuration settings on demand without causing an application to restart. 可以这样实现这一点:首先从配置提供程序的选项中获取 IConfigurationRefresher 的实例,然后在代码中的任何位置调用该实例上的 TryRefreshAsyncThis can be implemented by first getting an instance of IConfigurationRefresher from the options for the configuration provider and then calling TryRefreshAsync on that instance anywhere in your code.

为了使设置保持更新并避免对配置存储区进行太多的调用,对每个设置使用了一个缓存。In order to keep the settings updated and avoid too many calls to the configuration store, a cache is used for each setting. 在设置的缓存值过期前,刷新操作不会更新该值,即使该值在配置存储区中已发生更改。Until the cached value of a setting has expired, the refresh operation does not update the value, even when the value has changed in the configuration store. 每个请求的默认过期时间为 30 秒,但是,如果需要,可以重写该过期时间。The default expiration time for each request is 30 seconds, but it can be overridden if required.

本教程演示如何在代码中实现动态配置更新。This tutorial shows how you can implement dynamic configuration updates in your code. 它建立在快速入门中介绍的应用之上。It builds on the app introduced in the quickstarts. 在继续操作之前,请先完成使用应用程序配置创建 .NET Core 应用Before you continue, finish Create a .NET Core app with App Configuration first.

你可以使用任何代码编辑器执行本教程中的步骤。You can use any code editor to do the steps in this tutorial. Visual Studio Code 是 Windows、macOS 和 Linux 平台上提供的一个卓越选项。Visual Studio Code is an excellent option that's available on the Windows, macOS, and Linux platforms.

在本教程中,你将了解如何执行以下操作:In this tutorial, you learn how to:

  • 设置 .NET Core 应用,使其能够更新配置以响应应用程序配置存储区中的更改。Set up your .NET Core app to update its configuration in response to changes in an App Configuration store.
  • 在应用程序中使用最新配置。Consume the latest configuration in your application.

先决条件Prerequisites

若要完成本教程,请安装 .NET Core SDKTo do this tutorial, install the .NET Core SDK.

如果没有 Azure 试用版订阅,请在开始前创建一个试用版订阅If you don't have an Azure trail subscription, create a trial subscription before you begin.

从应用配置重载数据Reload data from App Configuration

打开 Program.cs 并更新文件以添加对 System.Threading.Tasks 命名空间的引用,在 AddAzureAppConfiguration 方法中指定刷新配置,并使用 TryRefreshAsync 方法触发手动刷新。Open Program.cs and update the file to add a reference to the System.Threading.Tasks namespace, to specify refresh configuration in the AddAzureAppConfiguration method, and to trigger manual refresh using the TryRefreshAsync method.

using System;
using System.Threading.Tasks;

namespace TestConsole
{
class Program
{
    private static IConfiguration _configuration = null;
    private static IConfigurationRefresher _refresher = null;

    static void Main(string[] args)
    {
        var builder = new ConfigurationBuilder();
        builder.AddAzureAppConfiguration(options =>
        {
            options.Connect(Environment.GetEnvironmentVariable("ConnectionString"))
                    .ConfigureRefresh(refresh =>
                    {
                        refresh.Register("TestApp:Settings:Message")
                               .SetCacheExpiration(TimeSpan.FromSeconds(10));
                    });
                    
                    _refresher = options.GetRefresher();
        });

        _configuration = builder.Build();
        PrintMessage().Wait();
    }

    private static async Task PrintMessage()
    {
        Console.WriteLine(_configuration["TestApp:Settings:Message"] ?? "Hello world!");

        // Wait for the user to press Enter
        Console.ReadLine();

        await _refresher.TryRefreshAsync();
        Console.WriteLine(_configuration["TestApp:Settings:Message"] ?? "Hello world!");
    }
}
}

ConfigureRefresh 方法用于指定在刷新操作触发时通过应用程序配置存储区更新配置数据所用的设置。The ConfigureRefresh method is used to specify the settings used to update the configuration data with the App Configuration store when a refresh operation is triggered. 可以在提供给 AddAzureAppConfiguration 方法的选项上调用 GetRefresher 方法,以便检索 IConfigurationRefresher 的实例,然后可以使用此实例上的 TryRefreshAsync 方法在代码中的任意位置触发刷新操作。An instance of IConfigurationRefresher can be retrieved by calling GetRefresher method on the options provided to AddAzureAppConfiguration method, and the TryRefreshAsync method on this instance could be used to trigger a refresh operation anywhere in your code.

备注

配置设置的默认缓存过期时间为 30 秒,但是,可以通过调用作为参数传递到 ConfigureRefresh 方法的选项初始值设定项上的 SetCacheExpiration 方法来重写该过期时间。The default cache expiration time for a configuration setting is 30 seconds, but can be overridden by calling the SetCacheExpiration method on the options initializer passed as an argument to the ConfigureRefresh method.

在本地生成并运行应用Build and run the app locally

  1. 设置名为“ConnectionString”的环境变量,并将其设置为应用程序配置存储区的访问密钥 。Set an environment variable named ConnectionString, and set it to the access key to your App Configuration store. 如果使用 Windows 命令提示符,则请运行以下命令并重启命令提示符,这样更改才会生效:If you use the Windows command prompt, run the following command and restart the command prompt to allow the change to take effect:

     setx ConnectionString "connection-string-of-your-app-configuration-store"
    

    如果使用 Windows PowerShell,请运行以下命令:If you use Windows PowerShell, run the following command:

     $Env:ConnectionString = "connection-string-of-your-app-configuration-store"
    

    如果使用 macOS 或 Linux,则请运行以下命令:If you use macOS or Linux, run the following command:

     export ConnectionString='connection-string-of-your-app-configuration-store'
    
  2. 运行以下命令以生成控制台应用:Run the following command to build the console app:

     dotnet build
    
  3. 生成成功完成后,请运行以下命令以在本地运行应用:After the build successfully completes, run the following command to run the app locally:

     dotnet run
    

    本地启动应用快速入门

  4. 登录 Azure 门户Sign in to the Azure portal. 选择“所有资源”,然后选择在快速入门中创建的应用程序配置存储区实例 。Select All resources, and select the App Configuration store instance that you created in the quickstart.

  5. 选择“配置资源管理器” 并更新以下键的值:Select Configuration Explorer, and update the values of the following keys:

    密钥Key Value
    TestApp:Settings:MessageTestApp:Settings:Message Azure 应用配置的数据 - 已更新Data from Azure App Configuration - Updated
  6. 按 Enter 键触发刷新并在命令提示符或 PowerShell 窗口中输出更新的值。Press the Enter key to trigger a refresh and print the updated value in the Command Prompt or PowerShell window.

    本地刷新应用快速入门

    备注

    由于在指定刷新操作的配置时已使用 SetCacheExpiration 方法将缓存过期时间设置为 10 秒,因此只有在针对该设置进行刷新并已过去至少 10 秒以后,才会更新此配置设置的值。Since the cache expiration time was set to 10 seconds using the SetCacheExpiration method while specifying the configuration for the refresh operation, the value for the configuration setting will only be updated if at least 10 seconds have elapsed since the last refresh for that setting.

清理资源Clean up resources

如果不想继续使用本文中创建的资源,请删除此处创建的资源组以避免产生费用。If you do not want to continue using the resources created in this article, delete the resource group you created here to avoid charges.

重要

删除资源组的操作不可逆。Deleting a resource group is irreversible. 将永久删除资源组以及其中的所有资源。The resource group and all the resources in it are permanently deleted. 请确保不要意外删除错误的资源组或资源。Make sure that you don't accidentally delete the wrong resource group or resources. 如果在包含要保留的其他资源的资源组中创建了本文的资源,请从相应的窗格中单独删除每个资源,而不是删除该资源组。If you created the resources for this article inside a resource group that contains other resources you want to keep, delete each resource individually from its respective pane instead of deleting the resource group.

  1. 登录到 Azure 门户,然后选择“资源组”。Sign in to the Azure portal, and select Resource groups.
  2. 在“按名称筛选”框中,输入资源组的名称。In the Filter by name box, enter the name of your resource group.
  3. 在结果列表中,选择资源组名称以查看概述。In the result list, select the resource group name to see an overview.
  4. 选择“删除资源组”。Select Delete resource group.
  5. 系统会要求确认是否删除资源组。You're asked to confirm the deletion of the resource group. 重新键入资源组的名称进行确认,然后选择“删除” 。Enter the name of your resource group to confirm, and select Delete.

片刻之后,将会删除该资源组及其所有资源。After a few moments, the resource group and all its resources are deleted.

后续步骤Next steps

在本教程中,你已启用 .NET Core 应用,以通过应用程序配置动态刷新配置设置。In this tutorial, you enabled your .NET Core app to dynamically refresh configuration settings from App Configuration. 若要了解如何使用 Azure 托管标识来简化对应用程序配置的访问,请继续学习下一篇教程。To learn how to use an Azure managed identity to streamline the access to App Configuration, continue to the next tutorial.