Durable Functions
Durable Functions is an extension of Azure Functions that allows you to write stateful functions in a serverless environment. It enables you to write workflows that can reliably orchestrate multiple functions and manage their state over time. Below is an example of a simple Durable Function in C#.
Firstly, you'll need to install the Microsoft.Azure.WebJobs.Extensions.DurableTask NuGet package.
### Example: Chaining Functions in a Durable Workflow
Let's create a durable function that calculates the factorial of a number. This example will use function chaining, where one function's output becomes another function's input.
```csharp
using System.Threading.Tasks;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
public static class FactorialCalculator
{
[FunctionName("FactorialOrchestrator")]
public static async Task RunOrchestrator(
[OrchestrationTrigger] IDurableOrchestrationContext context,
ILogger log)
{
var input = context.GetInput<int>();
// Replace "hello" with the name of your Durable Activity Function.
return await context.CallActivityAsync<int>("FactorialActivity", input);
}
[FunctionName("FactorialActivity")]
public static int RunActivity([ActivityTrigger] int number, ILogger log)
{
int result = 1;
for (int i = 1; i <= number; i++)
{
result *= i;
}
return result;
}
[FunctionName("HttpStart")]
public static async Task<HttpResponseMessage> HttpStart(
[HttpTrigger(AuthorizationLevel.Function, "get", "post")] HttpRequest req,
[DurableClient] IDurableOrchestrationClient starter,
ILogger log)
{
// Retrieve the number from the query string
int.TryParse(req.Query["number"], out int number);
// Function input comes from the request content.
string instanceId = await starter.StartNewAsync("FactorialOrchestrator", null, number);
log.LogInformation($"Started orchestration with ID = '{instanceId}'.");
return starter.CreateCheckStatusResponse(req, instanceId);
}
}
```
In this example:
- `FactorialOrchestrator` is the orchestrator function that defines the workflow. It takes an integer input, calls the `FactorialActivity` function, and returns the result.
- `FactorialActivity` is the activity function that calculates the factorial of the input number.
- `HttpStart` is an HTTP-triggered function that starts the orchestrator. You can initiate the orchestration by making an HTTP request to this function and passing the `number` parameter in the query string.
To run this example, you need to create an Azure Functions application, configure Durable Functions, and deploy the code to Azure. Then, you can trigger the workflow by making an HTTP request to the `HttpStart` endpoint with the `number` parameter specifying the input number for which you want to calculate the factorial.