How to inject service in Durable Function?

zmsoft 470 Reputation points
2025-02-27T06:09:12.67+00:00

Hi there,

In normal http trigger functions, it is easy to inject dependent services. But in a durable function, don't know how to inject services

public class ParallelOrchastratorCall
{
    private static IXXXService _xxxService;
    public ParallelOrchastratorCall(IXXXService xxxService)
    {
        _xxxService = xxxService;
    }

    [Function(nameof(ParallelOrchastratorCall))]
    public static async Task<List<string>> RunOrchestrator(
        [OrchestrationTrigger] TaskOrchestrationContext context)
    {
        ILogger logger = context.CreateReplaySafeLogger(nameof(ParallelOrchastratorCall));
        logger.LogInformation("Saying hello.");
        //Get list
        string[] list = {};
        // Fan-out
        var parallelTasks = new List<Task<string>>();
        List<string> result = new List<string>();
        
        for (int i = 0; i< list.Length; i++)
        {
            Task<string> task = context.CallActivityAsync<string>("xxx", list[i]);
            parallelTasks.Add(task);
        }
        //Wait for all tasks to complete
        await Task.WhenAll(parallelTasks);
        // Fan-in/reduce step
        foreach (var task in parallelTasks) 
            result.Add(task.Result);
        return result;
    }
  
    [Function(nameof(xxx))]
    public static async Task<string> xxx([ActivityTrigger] string name, FunctionContext executionContext)
    {
        Task<string> response = _xxxService.GeXXXByXXX(name);
        return await response;
    }
    [Function("ParallelOrchastratorCall_HttpStart")]
    public static async Task<HttpResponseData> HttpStart(
        [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post")] HttpRequestData req,
        [DurableClient] DurableTaskClient client,
        FunctionContext executionContext)
    {
        ILogger logger = executionContext.GetLogger("ParallelOrchastratorCall_HttpStart");
        // Function input comes from the request content.
        string instanceId = await client.ScheduleNewOrchestrationInstanceAsync(
            nameof(ParallelOrchastratorCall));
        logger.LogInformation("Started orchestration with ID = '{instanceId}'.", instanceId);
        // Returns an HTTP 202 response with an instance management payload.
        // See https://learn.microsoft.com/azure/azure-functions/durable/durable-functions-http-api#start-orchestration
        return await client.CreateCheckStatusResponseAsync(req, instanceId);
    }
}

Thanks&Regards,

zmsoft

Azure Functions
Azure Functions
An Azure service that provides an event-driven serverless compute platform.
5,909 questions
0 comments No comments
{count} votes

Accepted answer
  1. RithwikBojja 3,055 Reputation points Microsoft External Staff Moderator
    2025-03-04T06:55:08.8766667+00:00

    Hi @zmsoft,

    To inject the services into durable functions, one has to inject the service in constructor of function class and use that service in Activity function rather than orchestration as below:

    Program.cs:

    
    using Microsoft.Azure.Functions.Worker;
    
    using Microsoft.Extensions.DependencyInjection;
    
    using Microsoft.Extensions.Hosting;
    
    using Microsoft.Extensions.Logging;
    
    var rith = new HostBuilder()
    
        .ConfigureFunctionsWebApplication()
    
        .ConfigureServices(services =>
    
        {
    
            services.AddSingleton<RithService, TestService>(); 
    
        })
    
        .Build();
    
    rith.Run();
    
    

    Function1.cs:

    
    using Microsoft.Azure.Functions.Worker.Http;
    
    using Microsoft.DurableTask;
    
    using Microsoft.DurableTask.Client;
    
    using Microsoft.Extensions.DependencyInjection;
    
    using Microsoft.Extensions.Hosting;
    
    using Microsoft.Extensions.Logging;
    
    using System.Collections.Generic;
    
    using System.Threading.Tasks;
    
    namespace FunctionApp4
    
    {
    
        public static class Function1
    
        {
    
            [Function(nameof(Function1))]
    
            public static async Task<List<string>> RunOrchestrator(
    
                [OrchestrationTrigger] TaskOrchestrationContext context)
    
            {
    
                ILogger rilg = context.CreateReplaySafeLogger(nameof(Function1));
    
                rilg.LogInformation("Starting orchestrator.");
    
                var routs = new List<string>();
    
                routs.Add(await context.CallActivityAsync<string>(nameof(SayHello), "Rithwik"));
    
                return routs;
    
            }
    
            [Function(nameof(SayHello))]
    
            public static string SayHello([ActivityTrigger] string name, FunctionContext executionContext)
    
            {
    
                ILogger rilg = executionContext.GetLogger(nameof(SayHello));
    
                rilg.LogInformation("Saying hello to {name}.", name);
    
                var service = executionContext.InstanceServices.GetRequiredService<RithService>();
    
                return service.Rith_Get(name);
    
            }
    
            [Function("Function1_HttpStart")]
    
            public static async Task<HttpResponseData> HttpStart(
    
                [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post")] HttpRequestData req,
    
                [DurableClient] DurableTaskClient client,
    
                FunctionContext executionContext)
    
            {
    
                ILogger rilg = executionContext.GetLogger("Function1_HttpStart");
    
                string instanceId = await client.ScheduleNewOrchestrationInstanceAsync(
    
                    nameof(Function1));
    
                return await client.CreateCheckStatusResponseAsync(req, instanceId);
    
            }
    
        }
    
        public interface RithService
    
        {
    
            string Rith_Get(string test);
    
        }
    
        public class TestService : RithService
    
        {
    
            public string Rith_Get(string test) => $"Hi {test}!";
    
        }
    
    }
    
    

    Output:

    enter image description here

    Hope this helps.

    If the answer is helpful, please click Accept Answer and kindly upvote it. If you have any further questions about this answer, please click Comment.

    1 person found this answer helpful.
    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.