Messaging with MassTransit and Azure Service Bus in .NET 7
Messaging with MassTransit and Azure Service Bus in .NET 7
• Azure, .NET, Messaging, Service Bus, MassTransit
• 10 min read
Azure Service Bus is a fully managed enterprise integration message broker. In this post, let’s explore an example of how to implement messaging in .NET leveraging Azure Service Bus and MassTransit, with topics and subscriptions.
MassTransit
Just to bring some context, let’s start with a brief introduction to MassTransit.
MassTransit1 is an open-source distributed application framework for .NET. It simplifies the development of message-based applications by providing abstractions and utilities for building robust, scalable, and loosely coupled systems. MassTransit supports multiple transport providers, including RabbitMQ, Azure Service Bus, and more. It also provides support for various messaging patterns like publish/subscribe, request/response, and routing.
Azure Service Bus
Similar to MassTransit, here’s a brief introduction to Azure Service Bus.
Azure Service Bus2 provides reliable and secure asynchronous messaging between applications and services. Azure Service Bus supports a set of cloud-based, message-oriented middleware technologies including reliable message queuing and durable publish/subscribe messaging.
The example
This example will target Azure Service Bus Topics and Subscriptions3, which is not something common to see with MassTransit examples. The idea is to have publishers and subscribers, where the publishers will publish messages to a Topic, and the subscribers will subscribe from the Subscription and receive the messages.
Azure Service Bus ARM Template
First of all the Azure Service Bus needs to be provisioned, by using the following ARM template:
{"$schema":"https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#","contentVersion":"1.0.0.0","parameters":{"serviceBusNamespaceName":{"type":"string","metadata":{"description":"Name of the Service Bus namespace"}},"serviceBusTopicName1":{"type":"string","metadata":{"description":"Name of the Topic"}},"serviceBusTopicName2":{"type":"string","metadata":{"description":"Name of the Topic"}},"serviceBusSubscriptionName1":{"type":"string","metadata":{"description":"Name of the Subscription"}},"serviceBusSubscriptionName2":{"type":"string","metadata":{"description":"Name of the Subscription"}},"location":{"type":"string","defaultValue":"[resourceGroup().location]","metadata":{"description":"Location for all resources."}}},"resources":[{"apiVersion":"2022-10-01-preview","name":"[parameters('serviceBusNamespaceName')]","type":"Microsoft.ServiceBus/namespaces","location":"[parameters('location')]","sku":{"name":"Standard"},"properties":{},"resources":[{"apiVersion":"2022-10-01-preview","name":"[parameters('serviceBusTopicName1')]","type":"topics","dependsOn":["[resourceId('Microsoft.ServiceBus/namespaces/', parameters('serviceBusNamespaceName'))]"],"properties":{},"resources":[{"apiVersion":"2022-10-01-preview","name":"[parameters('serviceBusSubscriptionName1')]","type":"Subscriptions","dependsOn":["[parameters('serviceBusTopicName1')]"],"properties":{}}]},{"apiVersion":"2022-10-01-preview","name":"[parameters('serviceBusTopicName2')]","type":"topics","dependsOn":["[resourceId('Microsoft.ServiceBus/namespaces/', parameters('serviceBusNamespaceName'))]"],"properties":{},"resources":[{"apiVersion":"2022-10-01-preview","name":"[parameters('serviceBusSubscriptionName2')]","type":"Subscriptions","dependsOn":["[parameters('serviceBusTopicName2')]"],"properties":{}}]}]}]}
To deploy this service, the easiest way is to click the repo “Deploy button”:
which will lead you to the following page on Azure Portal:
From there you can simply provide the params and deploy the service, by clicking Review+Create and then Create.
The entity and events
The example will use a simple entity called Product and two record events ProductCreatedEvent and ProductUpdatedEvent. The ProductCreatedEvent event will be published when a product is created, and the ProductUpdatedEvent event will be published when a product is modified/updated.
The Publisher, which is an API, will expose three endpoints, the first for creating a product, the second for updating a product, and the third for scheduling a product creation. The endpoints will publish the corresponding event to an Azure Service Bus Topic.
To start, this is how the middleware is initialized:
NOTE: Retries are configured to retry 3 times with a 5 seconds interval. Another thing to notice is that to indicate the Topic to publish the message to, we use the SetEntityName method.
The Service Bus connection string is retrieved from the local.settings.json file:
publicclassEndpoints{privatereadonlyIPublishEndpoint_publisher;privatereadonlyIMessageScheduler_scheduler;privatereadonlyILogger_logger;publicEndpoints(ILoggerFactoryloggerFactory,IPublishEndpointpublisher,IMessageSchedulerscheduler){_publisher=publisher;_scheduler=scheduler;_logger=loggerFactory.CreateLogger<Endpoints>();} [Function(nameof(ProductCreated))]publicasyncTaskProductCreated([HttpTrigger(AuthorizationLevel.Function,"post")]HttpRequestDatareq){_logger.LogInformation("C# HTTP trigger function processed a request.");varproductCreatedEvent=awaitreq.ReadFromJsonAsync<ProductCreatedEvent>();if(productCreatedEvent!=null){await_publisher.Publish(productCreatedEvent,CancellationToken.None);_logger.LogInformation($"Product created: {productCreatedEvent.Id} - {productCreatedEvent.Name} - {productCreatedEvent.Sku}");}} [Function(nameof(ProductUpdated))]publicasyncTaskProductUpdated([HttpTrigger(AuthorizationLevel.Function,"put")]HttpRequestDatareq){_logger.LogInformation("C# HTTP trigger function processed a request.");varproductUpdatedEvent=awaitreq.ReadFromJsonAsync<ProductUpdatedEvent>();if(productUpdatedEvent!=null){await_publisher.Publish(productUpdatedEvent,CancellationToken.None);_logger.LogInformation($"Product updated: {productUpdatedEvent.Id} - {productUpdatedEvent.Name} - {productUpdatedEvent.Sku}");}} [Function(nameof(ProductCreatedScheduled))]publicasyncTaskProductCreatedScheduled([HttpTrigger(AuthorizationLevel.Function,"post")]HttpRequestDatareq){_logger.LogInformation("C# HTTP trigger function processed a request.");varproductCreatedEvent=awaitreq.ReadFromJsonAsync<ProductCreatedEvent>();if(productCreatedEvent!=null){await_scheduler.SchedulePublish(DateTime.UtcNow+TimeSpan.FromSeconds(20),productCreatedEvent);_logger.LogInformation($"Product created scheduled: {productCreatedEvent.Id} - {productCreatedEvent.Name} - {productCreatedEvent.Sku}");}}}
NOTE: IPublishEndpoint will be used to Publish the messages to the broker, and IMessageScheduler will be used to schedule the messages.
Subscriber
The Subscriber, which is a console application, will consume the events from Azure Service Bus Subscription and print the event details to the console.
To start, this is how the middleware is initialized:
NOTE: Consumers are added to the container, and the QueueProductCreatedConsumerDefinition and QueueProductUpdatedConsumerDefinition are used to configure the consumers. We also configured the consumer to consume the messages from the Subscription, and that is done using the SubscriptionEndpoint method. This is possible because the Topic was specified in previous lines using the SetEntityName method.
The Azure Service Bus connection string is retrieved from the appsettings.json file:
The class QueueProductCreatedConsumer implements the IConsumer<ProductCreatedEvent> interface, and the class QueueProductUpdatedConsumer implements the IConsumer<ProductUpdatedEvent> interface.
NOTE: In both consumers, the ConsumerDefinition is used to configure the retry policy, which means that if the consumer fails to process the message, it will retry 3 times with a 5 seconds interval. This could be configured differently for each consumer if needed.
Testing
To test the application, start the Container, then the Publisher and Subscriber projects.
By using one of the .http requests product-created.http of the Publisher project, trigger it from VStudio:
Join the conversation! Share your thoughts and connect with other readers.