0
Azure Service Bus enables enterprise messaging between distributed components. In ASP.NET Core, message consumption can be handled continuously using hosted background services.
Setting Up Azure.Messaging.ServiceBus
Install the official Azure.Messaging.ServiceBus library to handle queues and topic subscriptions.
Creating a Custom Hosted Background Service
Inherit from BackgroundService and manage the lifecycle of ServiceBusProcessor:
using Azure.Messaging.ServiceBus;
using Microsoft.Extensions.Hosting;
public class QueueConsumerService : BackgroundService
{
private readonly ServiceBusProcessor _processor;
public QueueConsumerService(ServiceBusClient client)
{
_processor = client.CreateProcessor("my-queue", new ServiceBusProcessorOptions());
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
_processor.ProcessMessageAsync += MessageHandler;
_processor.ProcessErrorAsync += ErrorHandler;
await _processor.StartProcessingAsync(stoppingToken);
}
private async Task MessageHandler(ProcessMessageEventArgs args)
{
string body = args.Message.Body.ToString();
await args.CompleteMessageAsync(args.Message);
}
private Task ErrorHandler(ProcessErrorEventArgs args)
{
return Task.CompletedTask;
}
}