Brighter and Azure: How to setup and use Brighter with Azure Service Bus

Introduction to Azure Service Bus Azure Service Bus is a fully managed enterprise message broker that facilitates reliable communication between applications and services, both in the cloud and hybrid environments. It supports message queues (point-to-point communication) and publish-subscribe topics (fan-out to multiple consumers), making it ideal for decoupling distributed systems. Brighter provides first-class integration with Azure Service Bus via the Paramore.Brighter.MessagingGateway.AzureServiceBus package, enabling seamless command/event routing in .NET applications. Requirement .NET 8 or superior A .NET project with these NuGet packages Paramore.Brighter.MessagingGateway.AzureServiceBus: Enables AWS SNS/SQS integration. Paramore.Brighter.ServiceActivator.Extensions.DependencyInjection: Bridge Brighter with Azure messaging services. Paramore.Brighter.ServiceActivator.Extensions.Hosting: Hosts Brighter as a background service. Serilog.AspNetCore: For structured logging (optional but recommended). Brighter Recap Before continuing about AWS SNS/SQS configuration, let's recap what we already know about Brighter. Request (Command/Event) Define messages using IRequest: public class Greeting() : Event(Guid.NewGuid()) { public string Name { get; set; } = string.Empty; } Commands: Single-recipient operations (e.g., SendEmail). Events: Broadcast notifications (e.g., OrderShipped). Message Mapper Translates between Brighter messages and your app objects: public class GreetingMapper : IAmAMessageMapper { public Message MapToMessage(Greeting request) { var header = new MessageHeader(); header.Id = request.Id; header.TimeStamp = DateTime.UtcNow; header.Topic = "greeting.topic"; // The target topic to be publish header.MessageType = MessageType.MT_EVENT; var body = new MessageBody(JsonSerializer.Serialize(request)); return new Message(header, body); } public Greeting MapToRequest(Message message) { return JsonSerializer.Deserialize(message.Body.Bytes)!; } } Request Handler Processes incoming messages: public class GreetingHandler(ILogger logger) : RequestHandler { public override Greeting Handle(Greeting command) { logger.LogInformation("Hello {Name}", command.Name); return base.Handle(command); } } Configuring Brighter with Azure Service Bus 1. Connection Setup Use Azure’s credential provider for secure authentication: var connection = new ServiceBusVisualStudioCredentialClientProvider(".servicebus.windows.net"); Alternatively, use a connection string: var connection = new ServiceBusConnectionStringClientProvider(""); 2. Azure Service Bus Subscription Subscribe to a queue/topic: .AddServiceActivator(opt => { opt.Subscriptions = [ new AzureServiceBusSubscription( new SubscriptionName("greeting-subscription"), // Optional new ChannelName("greeting-queue"), // Queue name new RoutingKey("greeting-topic"), // Topic Name bufferSize: 2) ]; opt.ChannelFactory = new AzureServiceBusChannelFactory(new AzureServiceBusConsumerFactory(connection, false)); }) 3. Azure Service Bus Producer Configuration Publish events to a topic: .UseExternalBus(new AzureServiceBusProducerRegistryFactory(connection, new[] { new AzureServiceBusPublication { Topic = new RoutingKey("greeting-topic"), MakeChannels = OnMissingChannel.Create } }).Create()); 4. Dead Letter Queues (DLQs) Enable DLQs to handle poisoned messages: opt.Subscriptions = [ new AzureServiceBusSubscription( subscriptionName: new SubscriptionName("greeting-subscription"), channelName: new ChannelName("greeting-queue"), routingKey: new RoutingKey("greeting-topic"), subscriptionConfiguration: new AzureServiceBusSubscriptionConfiguration { DeadLetteringOnMessageExpiration = true // Enable DLQ }, bufferSize: 2 ) ]; Azure Service Bus automatically moves expired or failed messages to a DLQ for inspection. Conclusion Integrating Brighter with Azure Service Bus enables robust, scalable messaging in .NET applications. By leveraging Azure’s managed infrastructure and Brighter's abstraction layer, you can: Decouple services with publish-subscribe patterns. Ensure message ordering and reliability. Simplify error handling with DLQs. For production use, always validate Azure Service Bus configurations against Brighter’s latest documentation. Reference Full code: Gi

May 5, 2025 - 09:24
 0
Brighter and Azure: How to setup and use Brighter with Azure Service Bus

Introduction to Azure Service Bus

Azure Service Bus is a fully managed enterprise message broker that facilitates reliable communication between applications and services, both in the cloud and hybrid environments. It supports message queues (point-to-point communication) and publish-subscribe topics (fan-out to multiple consumers), making it ideal for decoupling distributed systems. Brighter provides first-class integration with Azure Service Bus via the Paramore.Brighter.MessagingGateway.AzureServiceBus package, enabling seamless command/event routing in .NET applications.

Requirement

Brighter Recap

Before continuing about AWS SNS/SQS configuration, let's recap what we already know about Brighter.

Request (Command/Event)

Define messages using IRequest:

public class Greeting() : Event(Guid.NewGuid())
{
    public string Name { get; set; } = string.Empty;
}
  • Commands: Single-recipient operations (e.g., SendEmail).
  • Events: Broadcast notifications (e.g., OrderShipped).

Message Mapper

Translates between Brighter messages and your app objects:

public class GreetingMapper : IAmAMessageMapper<Greeting>
{
    public Message MapToMessage(Greeting request)
    {
        var header = new MessageHeader();
        header.Id = request.Id; 
        header.TimeStamp = DateTime.UtcNow;
        header.Topic = "greeting.topic"; // The target topic to be publish
        header.MessageType = MessageType.MT_EVENT;

        var body = new MessageBody(JsonSerializer.Serialize(request));
        return new Message(header, body);
    }

    public Greeting MapToRequest(Message message)
    {
        return JsonSerializer.Deserialize<Greeting>(message.Body.Bytes)!;
    }
}

Request Handler

Processes incoming messages:

public class GreetingHandler(ILogger<GreetingHandler> logger) : RequestHandler<Greeting>
{
    public override Greeting Handle(Greeting command)
    {
        logger.LogInformation("Hello {Name}", command.Name);
        return base.Handle(command);
    }
}

Configuring Brighter with Azure Service Bus

1. Connection Setup

Use Azure’s credential provider for secure authentication:

var connection = new ServiceBusVisualStudioCredentialClientProvider(".servicebus.windows.net");

Alternatively, use a connection string:

var connection = new ServiceBusConnectionStringClientProvider("");

2. Azure Service Bus Subscription

Subscribe to a queue/topic:

 .AddServiceActivator(opt =>
            {
                opt.Subscriptions = [
                    new AzureServiceBusSubscription<Greeting>(
                        new SubscriptionName("greeting-subscription"), // Optional
                        new ChannelName("greeting-queue"), // Queue name
                        new RoutingKey("greeting-topic"), // Topic Name
                        bufferSize: 2)
                ];
                opt.ChannelFactory = new AzureServiceBusChannelFactory(new AzureServiceBusConsumerFactory(connection, false));
            })

3. Azure Service Bus Producer Configuration

Publish events to a topic:

.UseExternalBus(new AzureServiceBusProducerRegistryFactory(connection, new[]
            {
                new AzureServiceBusPublication
                {
                    Topic = new RoutingKey("greeting-topic"),
                    MakeChannels = OnMissingChannel.Create
                }
            }).Create());

4. Dead Letter Queues (DLQs)

Enable DLQs to handle poisoned messages:

opt.Subscriptions = [
    new AzureServiceBusSubscription<Greeting>(
        subscriptionName: new SubscriptionName("greeting-subscription"),
        channelName: new ChannelName("greeting-queue"),
        routingKey: new RoutingKey("greeting-topic"),
        subscriptionConfiguration: new AzureServiceBusSubscriptionConfiguration
        {
            DeadLetteringOnMessageExpiration = true // Enable DLQ
        },
        bufferSize: 2
    )
];

Azure Service Bus automatically moves expired or failed messages to a DLQ for inspection.

Conclusion

Integrating Brighter with Azure Service Bus enables robust, scalable messaging in .NET applications. By leveraging Azure’s managed infrastructure and Brighter's abstraction layer, you can:

  • Decouple services with publish-subscribe patterns.
  • Ensure message ordering and reliability.
  • Simplify error handling with DLQs.

For production use, always validate Azure Service Bus configurations against Brighter’s latest documentation.

Reference