Skip to content

Commit ba7f86c

Browse files
committed
Update Azure Functions documents to .NET 8 isolated model
1 parent 87c5266 commit ba7f86c

File tree

2 files changed

+227
-245
lines changed

2 files changed

+227
-245
lines changed

articles/azure-app-configuration/enable-dynamic-configuration-azure-functions-csharp.md

Lines changed: 91 additions & 145 deletions
Original file line numberDiff line numberDiff line change
@@ -16,188 +16,139 @@ ms.tgt_pltfrm: Azure Functions
1616
---
1717
# Tutorial: Use dynamic configuration in an Azure Functions app
1818

19-
The App Configuration .NET configuration provider supports caching and refreshing configuration dynamically driven by application activity. This tutorial shows how you can implement dynamic configuration updates in your code. It builds on the Azure Functions app introduced in the quickstarts. Before you continue, finish [Create an Azure functions app with Azure App Configuration](./quickstart-azure-functions-csharp.md) first.
19+
This tutorial shows how you can enable dynamic configuration updates in your Azure Functions app. It builds upon the Azure Functions app introduced in the quickstarts. Before you continue, finish [Create an Azure functions app with Azure App Configuration](./quickstart-azure-functions-csharp.md) first.
2020

2121
In this tutorial, you learn how to:
2222

2323
> [!div class="checklist"]
24-
> * Set up your Azure Functions app to update its configuration in response to changes in an App Configuration store.
25-
> * Inject the latest configuration to your Azure Functions calls.
24+
> * Set up dynamic configuration refresh for your Azure Functions app.
25+
> * Enable automatic configuration refresh using App Configuraion middleware.
26+
> * Use the latest configuration in Function calls when changes occur in your App Configuration store.
2627
2728
## Prerequisites
2829

29-
- Azure subscription - [create one for free](https://azure.microsoft.com/free/)
30-
- [Visual Studio](https://visualstudio.microsoft.com/vs) with the **Azure development** workload
31-
- [Azure Functions tools](../azure-functions/functions-develop-vs.md), if it's not installed already with Visual Studio.
3230
- Finish quickstart [Create an Azure functions app with Azure App Configuration](./quickstart-azure-functions-csharp.md)
3331

3432
## Reload data from App Configuration
3533

36-
Azure Functions support running [in-process](../azure-functions/functions-dotnet-class-library.md) or [isolated-process](../azure-functions/dotnet-isolated-process-guide.md). The main difference in App Configuration usage between the two modes is how the configuration is refreshed. In the in-process mode, you must make a call in each function to refresh the configuration. In the isolated-process mode, there is support for middleware. The App Configuration middleware, `Microsoft.Azure.AppConfiguration.Functions.Worker`, enables the call to refresh configuration automatically before each function is executed.
34+
The Azure App Configuration .NET provider supports caching and dynamic refresh of configuration settings based on application activity. In this section, you configure the provider to refresh settings dynamically and enable automatic configuration refresh using the App Configuration middleware, `Microsoft.Azure.AppConfiguration.Functions.Worker`, each time a function executes.
3735

38-
1. Update the code that connects to App Configuration and add the data refreshing conditions.
39-
40-
### [In-process](#tab/in-process)
41-
42-
Open *Startup.cs*, and update the `ConfigureAppConfiguration` method.
36+
> [!NOTE]
37+
> Azure App Configuration can be used with Azure Functions in either the [isolated worker model](../azure-functions/dotnet-isolated-process-guide.md) or the [in-process model](../azure-functions/functions-dotnet-class-library.md). This tutorial uses the isolated worker model as an example. You can find complete code examples for both models in the [Azure App Configuration GitHub repository](https://github.com/Azure/AppConfiguration/tree/main/examples/DotNetCore/AzureFunctions).
4338
39+
1. Open the *Program.cs* file and update the call to `AddAzureAppConfiguration` to include the `ConfigureRefresh` method. This method configures the conditions for refreshing configuration settings, including specifying the keys to monitor and the interval between refresh checks.
4440

41+
### [Microsoft Entra ID (recommended)](#tab/entra-id)
42+
4543
```csharp
46-
public override void ConfigureAppConfiguration(IFunctionsConfigurationBuilder builder)
44+
// Connect to Azure App Configuration
45+
builder.Configuration.AddAzureAppConfiguration(options =>
4746
{
48-
builder.ConfigurationBuilder.AddAzureAppConfiguration(options =>
49-
{
50-
options.Connect(Environment.GetEnvironmentVariable("ConnectionString"))
51-
// Load all keys that start with `TestApp:` and have no label
52-
.Select("TestApp:*")
53-
// Configure to reload configuration if the registered sentinel key is modified
54-
.ConfigureRefresh(refreshOptions =>
55-
refreshOptions.Register("TestApp:Settings:Sentinel", refreshAll: true));
56-
});
57-
}
47+
Uri endpoint = new(Environment.GetEnvironmentVariable("AZURE_APPCONFIG_ENDPOINT") ??
48+
throw new InvalidOperationException("The environment variable 'AZURE_APPCONFIG_ENDPOINT' is not set or is empty."));
49+
options.Connect(endpoint, new DefaultAzureCredential())
50+
// Load all keys that start with `TestApp:` and have no label
51+
.Select("TestApp:*")
52+
// Reload configuration if any selected key-values have changed.
53+
// Use the default refresh interval of 30 seconds. It can be overridden via AzureAppConfigurationRefreshOptions.SetRefreshInterval.
54+
.ConfigureRefresh(refreshOptions =>
55+
{
56+
refreshOptions.RegisterAll();
57+
});
58+
});
5859
```
5960

60-
### [Isolated process](#tab/isolated-process)
61-
62-
Open *Program.cs*, and update the `Main` method.
61+
### [Connection string](#tab/connection-string)
6362

6463
```csharp
65-
public static void Main()
64+
// Connect to Azure App Configuration
65+
builder.Configuration.AddAzureAppConfiguration(options =>
6666
{
67-
var host = new HostBuilder()
68-
.ConfigureAppConfiguration(builder =>
69-
{
70-
builder.AddAzureAppConfiguration(options =>
71-
{
72-
options.Connect(Environment.GetEnvironmentVariable("ConnectionString"))
73-
// Load all keys that start with `TestApp:` and have no label
74-
.Select("TestApp:*")
75-
// Configure to reload configuration if the registered sentinel key is modified
76-
.ConfigureRefresh(refreshOptions =>
77-
refreshOptions.Register("TestApp:Settings:Sentinel", refreshAll: true));
78-
});
79-
})
80-
.ConfigureFunctionsWorkerDefaults()
81-
.Build();
82-
83-
host.Run();
84-
}
67+
string connectionString = Environment.GetEnvironmentVariable("AZURE_APPCONFIG_CONNECTION_STRING") ??
68+
throw new InvalidOperationException("The environment variable 'AZURE_APPCONFIG_CONNECTION_STRING' is not set or is empty.");
69+
options.Connect(connectionString)
70+
// Load all keys that start with `TestApp:` and have no label
71+
.Select("TestApp:*")
72+
// Reload configuration if any selected key-values have changed.
73+
// Use the default refresh interval of 30 seconds. It can be overridden via AzureAppConfigurationRefreshOptions.SetRefreshInterval.
74+
.ConfigureRefresh(refreshOptions =>
75+
{
76+
refreshOptions.RegisterAll();
77+
});
78+
});
8579
```
8680
---
8781

88-
The `ConfigureRefresh` method registers a setting to be checked for changes whenever a refresh is triggered within the application. The `refreshAll` parameter instructs the App Configuration provider to reload the entire configuration whenever a change is detected in the registered setting.
89-
90-
All settings registered for refresh have a default cache expiration of 30 seconds before a new refresh is attempted. It can be updated by calling the `AzureAppConfigurationRefreshOptions.SetCacheExpiration` method.
82+
You call the `RegisterAll` method to instruct the App Configuration provider to reload the entire configuration whenever a change is detected in any of the selected key-values (those starting with `TestApp:` and having no label).
9183

92-
> [!TIP]
93-
> When you are updating multiple key-values in App Configuration, you normally don't want your application to reload configuration before all changes are made. You can register a *sentinel key* and update it only when all other configuration changes are completed. This helps to ensure the consistency of configuration in your application.
94-
>
95-
> You may also do the following to minimize the risk of inconsistencies:
96-
>
97-
> * Design your application to be tolerable for transient configuration inconsistency
98-
> * Warm-up your application before bringing it online (serving requests)
99-
> * Carry default configuration in your application and use it when configuration validation fails
100-
> * Choose a configuration update strategy that minimizes the impact to your application, for example, a low traffic timing.
84+
By default, the refresh interval is set to 30 seconds. You can customize this interval by calling the `AzureAppConfigurationRefreshOptions.SetRefreshInterval` method.
10185

102-
103-
### [In-process](#tab/in-process)
104-
105-
2. Update the `Configure` method to make Azure App Configuration services available through dependency injection.
86+
1. Update the *Program.cs* file to enable automatic configuration refresh upon each function execution by adding the App Configuration middleware:
10687

10788
```csharp
108-
public override void Configure(IFunctionsHostBuilder builder)
89+
// Connect to Azure App Configuration
90+
builder.Configuration.AddAzureAppConfiguration(options =>
10991
{
110-
builder.Services.AddAzureAppConfiguration();
111-
}
112-
```
92+
// Omitted the code added in the previous step.
93+
});
11394

114-
3. Open *Function1.cs*, and add the following namespaces.
95+
// Add Azure App Configuration middleware to the service collection.
96+
builder.Services.AddAzureAppConfiguration()
11597

116-
```csharp
117-
using System.Linq;
118-
using Microsoft.Extensions.Configuration.AzureAppConfiguration;
98+
// Use Azure App Configuration middleware for dynamic configuration refresh.
99+
builder.UseAzureAppConfiguration();
100+
101+
builder.ConfigureFunctionsWebApplication();
102+
103+
builder.Build().Run();
119104
```
120105

121-
Update the constructor to obtain the instance of `IConfigurationRefresherProvider` through dependency injection, from which you can obtain the instance of `IConfigurationRefresher`.
106+
## Test the function locally
122107

123-
```csharp
124-
private readonly IConfiguration _configuration;
125-
private readonly IConfigurationRefresher _configurationRefresher;
108+
1. Set the environment variable.
126109

127-
public Function1(IConfiguration configuration, IConfigurationRefresherProvider refresherProvider)
128-
{
129-
_configuration = configuration;
130-
_configurationRefresher = refresherProvider.Refreshers.First();
131-
}
132-
```
110+
### [Microsoft Entra ID (recommended)](#tab/entra-id)
111+
Set the environment variable named **AZURE_APPCONFIG_ENDPOINT** to the endpoint of your App Configuration store found under the *Overview* of your store in the Azure portal.
133112

134-
4. Update the `Run` method and signal to refresh the configuration using the `TryRefreshAsync` method at the beginning of the Functions call. It will be a no-op if the cache expiration time window isn't reached. Remove the `await` operator if you prefer the configuration to be refreshed without blocking the current Functions call. In that case, later Functions calls will get updated value.
113+
If you use the Windows command prompt, run the following command and restart the command prompt to allow the change to take effect:
135114

136-
```csharp
137-
public async Task<IActionResult> Run(
138-
[HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req, ILogger log)
139-
{
140-
log.LogInformation("C# HTTP trigger function processed a request.");
115+
```cmd
116+
setx AZURE_APPCONFIG_ENDPOINT "<endpoint-of-your-app-configuration-store>"
117+
```
141118

142-
await _configurationRefresher.TryRefreshAsync();
119+
If you use PowerShell, run the following command:
143120

144-
string keyName = "TestApp:Settings:Message";
145-
string message = _configuration[keyName];
146-
147-
return message != null
148-
? (ActionResult)new OkObjectResult(message)
149-
: new BadRequestObjectResult($"Please create a key-value with the key '{keyName}' in App Configuration.");
150-
}
121+
```powershell
122+
$Env:AZURE_APPCONFIG_ENDPOINT = "<endpoint-of-your-app-configuration-store>"
151123
```
152124

153-
### [Isolated process](#tab/isolated-process)
154-
2. Add a `ConfigureServices` call to the `HostBuilder` to make Azure App Configuration services available through dependency injection. Then update the `ConfigureFunctionsWorkerDefaults` to use App Configuration middleware for configuration data refresh.
155-
156-
```csharp
157-
public static void Main()
158-
{
159-
var host = new HostBuilder()
160-
.ConfigureAppConfiguration(builder =>
161-
{
162-
// Omitted the code added in the previous step.
163-
// ... ...
164-
})
165-
.ConfigureServices(services =>
166-
{
167-
// Make Azure App Configuration services available through dependency injection.
168-
services.AddAzureAppConfiguration();
169-
})
170-
.ConfigureFunctionsWorkerDefaults(app =>
171-
{
172-
// Use Azure App Configuration middleware for data refresh.
173-
app.UseAzureAppConfiguration();
174-
})
175-
.Build();
176-
177-
host.Run();
178-
}
125+
If you use macOS or Linux, run the following command:
126+
127+
```bash
128+
export AZURE_APPCONFIG_ENDPOINT='<endpoint-of-your-app-configuration-store>'
179129
```
180-
---
181130

182-
## Test the function locally
131+
### [Connection string](#tab/connection-string)
132+
Set the environment variable named **AZURE_APPCONFIG_CONNECTION_STRING** to the read-only connection string of your App Configuration store found under *Access keys* of your store in the Azure portal.
183133

184-
1. Set an environment variable named **ConnectionString**, and set it to the access key to your app configuration store. If you use the Windows command prompt, run the following command and restart the command prompt to allow the change to take effect:
134+
If you use the Windows command prompt, run the following command and restart the command prompt to allow the change to take effect:
185135

186-
```console
187-
setx ConnectionString "<connection-string-of-your-app-configuration-store>"
136+
```cmd
137+
setx AZURE_APPCONFIG_CONNECTION_STRING "<connection-string-of-your-app-configuration-store>"
188138
```
189139

190-
If you use Windows PowerShell, run the following command:
140+
If you use PowerShell, run the following command:
191141

192142
```powershell
193-
$Env:ConnectionString = "<connection-string-of-your-app-configuration-store>"
143+
$Env:AZURE_APPCONFIG_CONNECTION_STRING = "<connection-string-of-your-app-configuration-store>"
194144
```
195145

196146
If you use macOS or Linux, run the following command:
197147

198-
```console
199-
export ConnectionString='<connection-string-of-your-app-configuration-store>'
200-
```
148+
```bash
149+
export AZURE_APPCONFIG_CONNECTION_STRING='<connection-string-of-your-app-configuration-store>'
150+
```
151+
---
201152

202153
2. To test your function, press F5. If prompted, accept the request from Visual Studio to download and install **Azure Functions Core (CLI)** tools. You might also need to enable a firewall exception so that the tools can handle HTTP requests.
203154

@@ -209,35 +160,30 @@ Azure Functions support running [in-process](../azure-functions/functions-dotnet
209160

210161
![Quickstart Function launch local](./media/quickstarts/dotnet-core-function-launch-local.png)
211162

212-
5. Sign in to the [Azure portal](https://portal.azure.com). Select **All resources**, and select the App Configuration store that you created in the quickstart.
213-
214-
6. Select **Configuration explorer**, and update the value of the following key:
163+
5. Select your App Configuration store in Azure portal and update the value of the following key in **Configuration explorer**.
215164

216165
| Key | Value |
217166
|---|---|
218-
| TestApp:Settings:Message | Data from Azure App Configuration - Updated |
167+
| *TestApp:Settings:Message* | *Data from Azure App Configuration - Updated* |
219168

220-
Then create the sentinel key or modify its value if it already exists, for example,
221-
222-
| Key | Value |
223-
|---|---|
224-
| TestApp:Settings:Sentinel | v1 |
225-
226-
227-
7. Refresh the browser a few times. When the cached setting expires after 30 seconds, the page shows the response of the Functions call with updated value.
169+
6. Refresh your browser a few times. After the default refresh interval of 30 seconds passes, the page displays the updated value retrieved from your Azure Functions app.
228170

229171
![Quickstart Function refresh local](./media/quickstarts/dotnet-core-function-refresh-local.png)
230172

231-
> [!NOTE]
232-
> The example code used in this tutorial can be downloaded from [App Configuration GitHub repo](https://github.com/Azure/AppConfiguration/tree/master/examples/DotNetCore/AzureFunction).
233-
234173
## Clean up resources
235174

236175
[!INCLUDE [azure-app-configuration-cleanup](../../includes/azure-app-configuration-cleanup.md)]
237176

238177
## Next steps
239178

240-
In this tutorial, you enabled your Azure Functions app to dynamically refresh configuration settings from App Configuration. To learn how to use an Azure managed identity to streamline the access to App Configuration, continue to the next tutorial.
179+
In this tutorial, you enabled your Azure Functions app to dynamically refresh configuration settings from App Configuration.
180+
181+
To learn how to use feature flags from Azure App Configuration within your Azure Functions app, proceed to the following tutorial.
182+
183+
> [!div class="nextstepaction"]
184+
> [Use feature flags in Azure Functions](./quickstart-feature-flag-azure-functions-csharp.md)
185+
186+
To learn how to use an Azure managed identity to streamline the access to App Configuration, continue to the following tutorial.
241187

242188
> [!div class="nextstepaction"]
243189
> [Access App Configuration using managed identity](./howto-integrate-azure-managed-service-identity.md)

0 commit comments

Comments
 (0)