Class MessageOutbox
Primary implementation of the outbox pattern for reliable message delivery with transactional guarantees. This component manages deferred message publishing to ensure consistency between business operations and message delivery, implementing at-least-once delivery semantics with configurable retry logic and error handling.
public sealed class MessageOutbox : IOutboxDispatcher, IAsyncDisposable, IDisposable
- Inheritance
-
MessageOutbox
- Implements
- Inherited Members
Constructors
MessageOutbox(IOutboxStore, IOutboxProcessor, DispatchJsonSerializer, IOptions<OutboxDeliveryOptions>, ILogger<MessageOutbox>)
Creates a dispatcher using the supplied processor. Sequential cycles must use the same processor identity.
public MessageOutbox(IOutboxStore outboxStore, IOutboxProcessor outboxProcessor, DispatchJsonSerializer serializer, IOptions<OutboxDeliveryOptions> options, ILogger<MessageOutbox> logger)
Parameters
outboxStoreIOutboxStoreThe message store.
outboxProcessorIOutboxProcessorThe processor owned by this dispatcher.
serializerDispatchJsonSerializerThe message serializer.
optionsIOptions<OutboxDeliveryOptions>The delivery options.
loggerILogger<MessageOutbox>The dispatcher logger.
MessageOutbox(IOutboxStore, DispatchJsonSerializer, IOptions<OutboxDeliveryOptions>, ILogger<MessageOutbox>, IServiceScopeFactory)
Creates a dispatcher with an independent processor scope for each dispatch cycle.
[ActivatorUtilitiesConstructor]
public MessageOutbox(IOutboxStore outboxStore, DispatchJsonSerializer serializer, IOptions<OutboxDeliveryOptions> options, ILogger<MessageOutbox> logger, IServiceScopeFactory scopeFactory)
Parameters
outboxStoreIOutboxStoreThe message store.
serializerDispatchJsonSerializerThe message serializer.
optionsIOptions<OutboxDeliveryOptions>The delivery options.
loggerILogger<MessageOutbox>The dispatcher logger.
scopeFactoryIServiceScopeFactoryThe factory owning each cycle's processor lifetime.
Methods
Dispose()
Disposes an idle dispatcher synchronously. Active cycles require asynchronous disposal.
public void Dispose()
DisposeAsync()
Performs asynchronous cleanup of outbox resources including processor disposal and connection cleanup. This method ensures proper resource cleanup and graceful shutdown of the outbox processing infrastructure.
public ValueTask DisposeAsync()
Returns
- ValueTask
ValueTask representing the asynchronous disposal operation.
GetPendingMessagesAsync(CancellationToken)
Retrieves all pending messages from the outbox that are ready for dispatch.
public Task<IEnumerable<IDispatchMessage>> GetPendingMessagesAsync(CancellationToken cancellationToken)
Parameters
cancellationTokenCancellationTokenCancellation token for operation timeout and cancellation support.
Returns
- Task<IEnumerable<IDispatchMessage>>
A task representing the asynchronous operation, with the result containing an enumerable collection of pending dispatch messages.
Remarks
This method provides read-only access to pending outbox messages for monitoring, diagnostics, and manual intervention scenarios. It does not modify message states or reserve messages for processing.
Message Selection Criteria:
Pending messages are typically those that:
- Have not been successfully processed yet
- Are not currently reserved by active dispatchers
- Have not exceeded maximum retry limits
- Are scheduled for immediate or past processing.
Operational Use Cases:
- Health monitoring and alerting on message queue depth
- Troubleshooting and diagnostics for failed message processing
- Manual message inspection and intervention
- Metrics collection and performance analysis.
Performance Considerations:
This operation may return large result sets in high-throughput scenarios. Consider implementing pagination or filtering for production monitoring systems.
RunOutboxDispatchAsync(string, CancellationToken)
Runs one outbox dispatch cycle. The host or scheduler owns repetition.
public Task<int> RunOutboxDispatchAsync(string dispatcherId, CancellationToken cancellationToken)
Parameters
dispatcherIdstringUnique identifier for this dispatcher instance, used for message ownership and coordination.
cancellationTokenCancellationTokenCancellation token to support graceful shutdown and timeout scenarios.
Returns
Exceptions
- ArgumentNullException
Thrown when dispatcherId is null or empty.
- InvalidOperationException
Thrown when the outbox processor cannot be initialized.
SaveEventsAsync(IReadOnlyCollection<IIntegrationEvent>, IMessageMetadata, CancellationToken)
Saves integration events to the outbox for deferred publishing with transactional guarantees. This method serializes events and metadata, applies TTL policies, and stores them for later processing by the outbox dispatcher, ensuring reliable message delivery with at-least-once semantics.
public Task SaveEventsAsync(IReadOnlyCollection<IIntegrationEvent> integrationEvents, IMessageMetadata metadata, CancellationToken cancellationToken)
Parameters
integrationEventsIReadOnlyCollection<IIntegrationEvent>Collection of integration events to save for deferred publishing.
metadataIMessageMetadataMessage metadata containing routing, correlation, and processing information.
cancellationTokenCancellationTokenCancellation token for operation timeout and shutdown support.
Returns
- Task
Task representing the asynchronous event saving operation.
Exceptions
- ArgumentNullException
Thrown when integrationEvents is null.
- SerializationException
Thrown when event or metadata serialization fails.
SaveMessagesAsync(ICollection<IOutboxMessage>, CancellationToken)
Saves pre-constructed outbox messages directly to the outbox store.
public Task<int> SaveMessagesAsync(ICollection<IOutboxMessage> outboxMessages, CancellationToken cancellationToken)
Parameters
outboxMessagesICollection<IOutboxMessage>Collection of fully prepared outbox messages ready for storage.
cancellationTokenCancellationTokenCancellation token for operation timeout and cancellation support.
Returns
- Task<int>
A task representing the asynchronous operation, with the result containing the number of messages successfully saved to the outbox.
Remarks
This method provides direct control over outbox message creation and storage, suitable for advanced scenarios where custom message formatting or routing logic is required.
Use Cases:
- Custom message serialization or encryption requirements
- Complex routing scenarios with multiple destinations
- Message transformation or enrichment logic
- Integration with external message formats or protocols.
Message Validation:
The implementation should validate that messages have required fields populated including message body, type information, and routing details before storage.
Transactional Context:
Like SaveEventsAsync, this operation should execute within an active database transaction to maintain consistency with associated business operations.
Exceptions
- ArgumentNullException
Thrown when outboxMessages is null.
- ArgumentException
Thrown when outboxMessages contains invalid or incomplete message data.
SignalNewMessage()
Retained for compatibility. This method does not schedule a dispatch cycle; the host owns scheduling.
public void SignalNewMessage()