How to get underlying MessageReceiver reference behind an Azure Service Bus triggered Azure Function V3

Viewed 422

I have configured my Azure Function not to 'autoComplete' messages when the Azure Function is triggered. My issue is I need to mark the message complete myself and do so in the context of a transaction (below). This transaction using the 'via' route works in a console app but fails in Azure due to a lack of reference to the original receiver which dequeued the message.

How to get the underlying receiver reference so I can complete and send atomically? There appears no way to do this in Azure Functions.

using (var ts = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
{
      try
      {
         await receiver.CompleteAsync(completeMessage.SystemProperties.LockToken);

         for (var i = 0; i <= sendMessages.Length - 1; i++)
            await sender.SendAsync(sendMessages[i]);

         ts.Complete();
      }
      catch (Exception ex)
      {
         // This rolls back send and complete in case an exception happens
      }
}

Without the original receiver reference (and your own newly created reference) you get the following Exception:

ERROR: Microsoft.Azure.ServiceBus.MessageLockLostException: The lock supplied is invalid. Either the lock expired, or the message has already been removed from the queue, or was received by a different receiver instance.
1 Answers

You need to inject the message receiver used by the Function to receive the incoming message. Injection is done via function parameters. This post goes into details.

Related