RabbitMqEventBus provides a robust implementation of the event bus pattern using RabbitMQ for asynchronous message publishing and subscription.
RabbitMqEventBus Implementation
Class Definition
Core.Infraestructure.EventBus.RabbitMq/Buses/RabbitMqEventBus.cs
Constructor
connectionManager: Manages RabbitMQ connectionslogger: Logger instance for diagnosticseventBusSubscriptionManager: Manages event subscriptionsserviceScopeFactory: Creates service scopes for event handlersqueueName: Name of the RabbitMQ queue (default: “CommonEventBus”)retryCont: Number of retry attempts (default: 3)
Publishing Events
Publish Method
Retry Policy
The publish operation uses Polly for exponential backoff retry:Subscribing to Events
Subscribe Method
Dynamic Subscription
Unsubscribe Methods
Connection Management
TheConnectionManager handles RabbitMQ connection lifecycle with automatic reconnection.
ConnectionManager
Core.Infraestructure.EventBus.RabbitMq/Managers/ConnectionManager.cs
Automatic Reconnection
The connection manager automatically handles:- Connection shutdown events
- Callback exceptions
- Connection blocked events
Configuration
RabbitMqOptions
Core.Infraestructure.EventBus.RabbitMq/RabbitMqOptions.cs
appsettings.json Configuration
Option 1: Using Connection StringService Registration
Register the event bus in your DI container:Core.Infraestructure.EventBus.RabbitMq/Extensions/EventBusExtensions.cs
Usage in Startup/Program.cs
Event Serialization
Events are serialized using Newtonsoft.Json:Complete Usage Example
1. Define Event
2. Create Handler
3. Register Handler
4. Subscribe to Event
5. Publish Event
Key Features
- Reliable Messaging: Persistent messages with delivery mode 2
- Automatic Retry: Exponential backoff for connection and publish failures
- Reconnection: Automatic reconnection on connection loss
- Direct Exchange: Uses RabbitMQ direct exchange for routing
- Async Consumers: Supports asynchronous message processing
- Scoped Services: Event handlers run in isolated service scopes
- Type Safety: Strongly-typed event handlers