Using an Azure Service Bus Topic Subscription in an Azure Function

This post shows how to consume Azure service bus topic subscriptions in an Azure function.

Code: https://github.com/damienbod/AspNetCoreServiceBus

Posts in this series:

History

  • 2024-06-30 Updated packages, Azure function
  • 2021-05-19 Updated .NET, Azure Service Bus SDK

Processing the Azure Service Bus Messages in an Azure Function

Setting this up could not be easier. In Visual Studio, create a new Azure function project, and then create a new Azure function using the Visual Studio helpers.

Select a Service Bus Topic trigger and add the definitions as required. These can be changed later, if you don’t know the required values.

The new Azure function has an attribute which is used to defined the client for the topic subscription. The service bus connection string is defined as ServiceBusConnectionString. This will be specified later. The message is then deserialized to an object. Now you can handle the payload as required.

using Azure.Messaging.ServiceBus;
using Microsoft.Azure.Functions.Worker;
using Microsoft.Extensions.Logging;

namespace FunctionService3;

public class MyQueueFunction
{
    private readonly ILogger<MyQueueFunction> _logger;

    public MyQueueFunction(ILogger<MyQueueFunction> logger)
    {
        _logger = logger;
    }

    [Function(nameof(MyQueueFunction))]
    public async Task Run([ServiceBusTrigger("myqueue", Connection = "ServiceBusConnectionString")]
        ServiceBusReceivedMessage message, ServiceBusMessageActions messageActions)
    {
        _logger.LogInformation("Message ID: {id}", message.MessageId);
        _logger.LogInformation("Message Body: {body}", message.Body);
        _logger.LogInformation("Message Content-Type: {contentType}", message.ContentType);

        // Complete the message
        await messageActions.CompleteMessageAsync(message);

        _logger.LogInformation("C# ServiceBus queue trigger function processed message: {myQueueItem}", message);
    }
}

The connection for the Azure service bus is defined in the secrets file. Azure Key Vault could also be used to get the service bus connection string.

{
    "IsEncrypted": false,
    "Values": {
        "AzureWebJobsStorage": "UseDevelopmentStorage=true",
        "FUNCTIONS_WORKER_RUNTIME": "dotnet-isolated"
    }
}

The Azure service bus subscription needs to be configured in Azure:

It is really easy to use Azure service bus with Azure functions. The handling of secrets could be improved. There are some open source projects which help solve this problem.

Links:

https://docs.microsoft.com/en-us/azure/service-bus-messaging/

https://docs.microsoft.com/en-us/azure/service-bus-messaging/service-bus-dotnet-get-started-with-queues

https://www.nuget.org/packages/Microsoft.Azure.ServiceBus

Azure Service Bus Topologies

https://docs.microsoft.com/en-us/dotnet/standard/microservices-architecture/multi-container-microservice-net-applications/integration-event-based-microservice-communications

Always subscribe to Dead-lettered messages when using an Azure Service Bus

https://ml-software.ch/posts/stripe-api-with-asp-net-core-part-3

8 comments

  1. Schmallaria's avatar
    Schmallaria · · Reply

    Could you please share some information on how to debug azure functions? Especially those which uses ServiceBusTrigger.

    1. damienbod's avatar

      Hi Schmallaria
      For local dev, this should just work. The example in this blog is committed to the git repo, and it should just start. You need to install to local tools to run azure functions. Or do you mean directly on the deployment, like in Azure?

      Greetings Damien

  2. Schmallaria's avatar
    Schmallaria · · Reply

    Hi Damien,

    Yes, I mean local debugging. Could you explain what tools I need and what I have to do to start debugging? When I try to debug a Azure function with a ServiceBusTrigger I always get the error: “Cannot start the Azure Storage Emulator. Please run AzureStorageEmulator.exe start”.

    BR

    1. damienbod's avatar

      I added the links for the tools here:

      Running Local Azure Functions in Visual Studio with HTTPS

      install the tools from the 3 links, and you will be able to debug, run locally

      Greetings Damien

      1. Schmallaria's avatar
        Schmallaria · ·

        Hi Damien,

        many thanks. That helped me. I had trouble with my localDB instance which was not correct configured thus the emulator didn’t start. After re-installing all required tools (mentioned in your link) everything is working as expected.

        BR

  3. DaveCline's avatar

    How might one create a service bus triggered function with a DYNAMIC connection string?

    Let’s say I have 4 different queues and depending on some configuration setting I want my functions to be configured with one or another of those service bus connection strings.

    I’ve looked at binding. Can’t see how that helps.

    I’ve looked at StartUp . Configure, but still, can’t get my Topic Triggered Functions to load correctly.

    Any ideas?

  4. Matt's avatar

    @DaveCline – Unfortunately you can’t as the connection string is required at instantiation time and is a read-only property. You’ll have to create multiple instances.

Leave a reply to damienbod Cancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.