Tutorial: Use dynamic configuration in a .NET Framework app
Data from App Configuration can be loaded as App Settings in a .NET Framework app. For more information, see the quickstart. However, as is designed by the .NET Framework, the App Settings can only refresh upon app restart. The App Configuration .NET provider is a .NET Standard library. It supports caching and refreshing configuration dynamically without app restart. This tutorial shows how you can implement dynamic configuration updates in a .NET Framework console app.
In this tutorial, you learn how to:
- Set up your .NET Framework app to update its configuration in response to changes in an App Configuration store.
- Inject the latest configuration in your application.
Prerequisites
- An Azure account with an active subscription. Create one for free.
- An App Configuration store. Create a store.
- Visual Studio
- .NET Framework 4.7.2 or later
Add a key-value
Add the following key-value to the App Configuration store and leave Label and Content Type with their default values. For more information about how to add key-values to a store using the Azure portal or the CLI, go to Create a key-value.
Key | Value |
---|---|
TestApp:Settings:Message | Data from Azure App Configuration |
Create a .NET Framework console app
Start Visual Studio and select Create a new project.
In Create a new project, filter on the Console project type and select Console App (.NET Framework) with C# from the project template list. Press Next.
In Configure your new project, enter a project name. Under Framework, select .NET Framework 4.7.2 or higher. Press Create.
Reload data from App Configuration
Right-click your project, and select Manage NuGet Packages. On the Browse tab, search and add the latest version of the following NuGet package to your project.
- Microsoft.Extensions.Configuration.AzureAppConfiguration
- Azure.Identity
Open Program.cs and add following namespaces.
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration.AzureAppConfiguration; using Azure.Identity;
Add two variables to store configuration-related objects.
private static IConfiguration _configuration; private static IConfigurationRefresher _refresher;
Update the
Main
method to connect to App Configuration with the specified refresh options. Connect to App Configuration using Microsoft Entra ID (recommended), or a connection string.You use the
DefaultAzureCredential
to authenticate to your App Configuration store. Follow the instructions to assign your credential the App Configuration Data Reader role. Be sure to allow sufficient time for the permission to propagate before running your application.// Existing code in Program.cs // ... ... static void Main(string[] args) { var builder = new ConfigurationBuilder(); builder.AddAzureAppConfiguration(options => { string endpoint = Environment.GetEnvironmentVariable("Endpoint"); options.Connect(new Uri(endpoint), new DefaultAzureCredential()) // Load all keys that start with `TestApp:`. .Select("TestApp:*") // Configure to reload the key 'TestApp:Settings:Message' if it is modified. .ConfigureRefresh(refresh => { refresh.Register("TestApp:Settings:Message") .SetCacheExpiration(TimeSpan.FromSeconds(10)); }); _refresher = options.GetRefresher(); }); _configuration = builder.Build(); PrintMessage().Wait(); } // The rest of existing code in Program.cs // ... ...
In the
ConfigureRefresh
method, a key within your App Configuration store is registered for change monitoring. TheRegister
method has an optional boolean parameterrefreshAll
that can be used to indicate whether all configuration values should be refreshed if the registered key changes. In this example, only the key TestApp:Settings:Message will be refreshed. TheSetCacheExpiration
method specifies the minimum time that must elapse before a new request is made to App Configuration to check for any configuration changes. In this example, you override the default expiration time of 30 seconds, specifying a time of 10 seconds instead for demonstration purposes.Add a method called
PrintMessage()
that triggers a refresh of configuration data from App Configuration.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!"); }
Calling the
ConfigureRefresh
method alone won't cause the configuration to refresh automatically. You call theTryRefreshAsync
method from the interfaceIConfigurationRefresher
to trigger a refresh. This design is to avoid requests sent to App Configuration even when your application is idle. You can include theTryRefreshAsync
call where you consider your application active. For example, it can be when you process an incoming message, an order, or an iteration of a complex task. It can also be in a timer if your application is active all the time. In this example, you callTryRefreshAsync
when you press the Enter key. Note that, even if the callTryRefreshAsync
fails for any reason, your application will continue to use the cached configuration. Another attempt will be made when the configured cache expiration time has passed and theTryRefreshAsync
call is triggered by your application activity again. CallingTryRefreshAsync
is a no-op before the configured cache expiration time elapses, so its performance impact is minimal, even if it's called frequently.
Build and run the app locally
Set an environment variable.
Set an environment variable named
Endpoint
to the endpoint of your App Configuration store found under the Overview of your store in the Azure portal.If you use the Windows command prompt, run the following command and restart the command prompt to allow the change to take effect:
setx Endpoint "<endpoint-of-your-app-configuration-store>"
If you use PowerShell, run the following command:
$Env:Endpoint = "<endpoint-of-your-app-configuration-store>"
If you use macOS or Linux, run the following command:
export Endpoint='<endpoint-of-your-app-configuration-store>'
Restart Visual Studio to allow the change to take effect.
Press Ctrl + F5 to build and run the console app.
In the Azure portal, navigate to the Configuration explorer of your App Configuration store, and update the value of the following key.
Key Value TestApp:Settings:Message Data from Azure App Configuration - Updated Back in the running application, press the Enter key to trigger a refresh and print the updated value in the Command Prompt or PowerShell window.
Note
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 don't want to continue using the resources created in this article, delete the resource group you created here to avoid charges.
Important
Deleting a resource group is irreversible. The resource group and all the resources in it are permanently deleted. Ensure 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.
- Sign in to the Azure portal, and select Resource groups.
- In the Filter by name box, enter the name of your resource group.
- In the result list, select the resource group name to see an overview.
- Select Delete resource group.
- 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
In this tutorial, you enabled your .NET Framework app to dynamically refresh configuration settings from App Configuration. To learn how to enable dynamic configuration in an ASP.NET Web Application (.NET Framework), continue to the next tutorial:
To learn how to use an Azure managed identity to streamline the access to App Configuration, continue to the next tutorial: