Search code examples
c#azureazure-functionsazureservicebus

Service Bus Processor Dependency Injection


I have an Azure function in which I am using the Service bus processor to receieve message from Service bus Topic while the function is running (Please note this is not the trigger). Based on the message receieved from the Topic, I am setting a CancellationToken.

I was able to move all the service bus related code in a separate service and injecting the ServiceBusClient in Program.cs:-

 builder.Services.AddAzureClients(clientBuilder =>
 {
     clientBuilder.AddServiceBusClientWithNamespace(serviceBusOptions.ServiceBusUri)
                  .WithCredential(new DefaultAzureCredential())
                  .ConfigureOptions(options =>
                   {
                          //
                   });
 }

But I am not sure if I can also inject the Service Bus Processor or if I can move this logic to a service. Based on the docmentation, it's recommended to be cached.

Current code (Inside function):-

 processor = queueService.GetProcessor(subscriptionName);
 processor.ProcessMessageAsync += async (ProcessSessionMessageEventArgs args) => {...} 
 processor.ProcessErrorAsync += Processor_ProcessErrorAsync;
 await processor.StartProcessingAsync();

I want to avoid keeping this code inside the main function class, is there any way to inject it or better write the same?

Edit: The function runs some sql stored procedures, at time the procedure might take time and user may request cancellation. Since there is no other way to stop the running instance of function, I went with this approach. Please suggest if there is any better way to stop a running function instance.


Solution

  • Just as someone pointed out already here, I have a similar feeling about this approach.

    The issue is with running a ServiceBusProcessor within a function. While technically it's possible, it's not designed for a short term execution. ServiceBusProcessor in it's own is a message pump. So is Azure function. Perhaps function based implementation is not the approach for this scenario.