Class MessageBusOutboxPublisher
Outbox publisher that stages messages for reliable delivery via a message bus. Supports multi-transport publishing with parallel delivery and per-transport status tracking.
[SuppressMessage("Maintainability", "CA1506:AvoidExcessiveClassCoupling", Justification = "Coordinates the existing serialization, transport, store, and retry-owner contracts for transactional publication; these dependencies belong to that composition boundary.")]
public sealed class MessageBusOutboxPublisher : IOutboxPublisher
- Inheritance
-
MessageBusOutboxPublisher
- Implements
- Inherited Members
- Extension Methods
Remarks
This implementation uses the transactional outbox pattern to ensure messages are reliably delivered even in the face of failures. Messages are first staged to the outbox store within the same transaction as the business operation, then published asynchronously by background processors.
Constructors
MessageBusOutboxPublisher(IOutboxStore, IPayloadSerializer, IMessageBusAdapter, IServiceProvider, ILogger<MessageBusOutboxPublisher>)
Initializes a new instance of the MessageBusOutboxPublisher class.
public MessageBusOutboxPublisher(IOutboxStore outboxStore, IPayloadSerializer serializer, IMessageBusAdapter messageBus, IServiceProvider serviceProvider, ILogger<MessageBusOutboxPublisher> logger)
Parameters
outboxStoreIOutboxStoreThe outbox store for message persistence.
serializerIPayloadSerializerThe payload serializer for message body serialization with pluggable format support.
messageBusIMessageBusAdapterThe message bus adapter for publishing (for single-transport mode).
serviceProviderIServiceProviderThe service provider for creating message contexts.
loggerILogger<MessageBusOutboxPublisher>The logger instance.
MessageBusOutboxPublisher(IOutboxStore, IPayloadSerializer, ITransportRegistry, IServiceProvider, ILogger<MessageBusOutboxPublisher>)
Initializes a new instance of the MessageBusOutboxPublisher class with multi-transport support.
public MessageBusOutboxPublisher(IOutboxStore outboxStore, IPayloadSerializer serializer, ITransportRegistry transportRegistry, IServiceProvider serviceProvider, ILogger<MessageBusOutboxPublisher> logger)
Parameters
outboxStoreIOutboxStoreThe outbox store for message persistence.
serializerIPayloadSerializerThe payload serializer for message body serialization with pluggable format support.
transportRegistryITransportRegistryThe transport registry for multi-transport publishing.
serviceProviderIServiceProviderThe service provider for creating message contexts.
loggerILogger<MessageBusOutboxPublisher>The logger instance.
Methods
GetStatistics()
Gets statistics about the outbox publisher performance.
public PublisherStatistics GetStatistics()
Returns
- PublisherStatistics
Publishing statistics including throughput and error rates.
PublishAsync(object, string, DateTimeOffset?, CancellationToken)
Stages a message in the outbox for later delivery.
public Task<OutboundMessage> PublishAsync(object message, string destination, DateTimeOffset? scheduledAt, CancellationToken cancellationToken)
Parameters
messageobjectThe message to publish.
destinationstringThe target destination (queue, topic, or endpoint).
scheduledAtDateTimeOffset?Optional time when the message should be processed. If null, process immediately.
cancellationTokenCancellationTokenCancellation token.
Returns
- Task<OutboundMessage>
The staged outbound message for tracking.
PublishMultiTransportAsync(object, IEnumerable<OutboundMessageTransport>, CancellationToken, DateTimeOffset?)
Publishes a message to multiple transports with per-transport delivery tracking.
public Task<OutboundMessage> PublishMultiTransportAsync(object message, IEnumerable<OutboundMessageTransport> transports, CancellationToken cancellationToken, DateTimeOffset? scheduledAt = null)
Parameters
messageobjectThe message to publish.
transportsIEnumerable<OutboundMessageTransport>The transport delivery configurations.
cancellationTokenCancellationTokenCancellation token.
scheduledAtDateTimeOffset?Optional scheduled delivery time.
Returns
- Task<OutboundMessage>
The staged outbound message.
PublishPendingMessagesAsync(CancellationToken)
Claims a batch of due messages from the outbox store and publishes it.
public Task<PublishingResult> PublishPendingMessagesAsync(CancellationToken cancellationToken)
Parameters
cancellationTokenCancellationTokenToken to monitor for cancellation requests.
Returns
- Task<PublishingResult>
The result of the publishing operation including success/failure counts.
Remarks
Implementations MUST win a lease before handing any message to a transport. The store's claim is an atomic read-decide-write, so concurrent drains receive disjoint batches. Selecting rows with a plain read and publishing them is check-then-act and admits double delivery, however narrow the read's filter.
The claim also decides which rows are due. It admits a message that is unclaimed (or whose lease has expired), whose scheduled time has arrived, and whose next-attempt floor has elapsed — so one drain covers immediate, scheduled and retry-eligible messages alike.
Exceptions
- OperationCanceledException
Thrown when the operation is cancelled.
PublishPendingTransportDeliveriesAsync(string, CancellationToken, int)
Publishes pending deliveries for a specific transport in parallel.
public Task<PublishingResult> PublishPendingTransportDeliveriesAsync(string transportName, CancellationToken cancellationToken, int batchSize = 100)
Parameters
transportNamestringThe transport name to process.
cancellationTokenCancellationTokenCancellation token.
batchSizeintMaximum number of deliveries to process.
Returns
- Task<PublishingResult>
The publishing result.
PublishScheduledMessagesAsync(CancellationToken)
Runs a drain pass that delivers scheduled messages whose time has arrived.
public Task<PublishingResult> PublishScheduledMessagesAsync(CancellationToken cancellationToken)
Parameters
cancellationTokenCancellationTokenToken to monitor for cancellation requests.
Returns
- Task<PublishingResult>
The result of the publishing operation including success/failure counts.
Remarks
A scheduled message is delivered by the same claim as every other message — the claim admits it once its scheduled time has passed — so this is a further pass of the drain described on PublishPendingMessagesAsync(CancellationToken) and carries the same lease requirement. It is not a second, unleased path: implementations MUST NOT satisfy it with a plain read of scheduled rows. A batch drained here may therefore also contain immediate or retry-eligible messages, which is deliberate — the claim is not category-selective, and filtering a claimed batch would strand the rows it discarded under a live lease.
Exceptions
- OperationCanceledException
Thrown when the operation is cancelled.
RetryFailedMessagesAsync(int, CancellationToken)
Runs a drain pass that redelivers failed messages whose backoff floor has elapsed.
public Task<PublishingResult> RetryFailedMessagesAsync(int maxRetries, CancellationToken cancellationToken)
Parameters
maxRetriesintMaximum number of retry attempts per message. Must not be negative.
cancellationTokenCancellationTokenToken to monitor for cancellation requests.
Returns
- Task<PublishingResult>
The result of the retry operation including success/failure counts.
Remarks
A failed message becomes deliverable again only once the next-attempt floor written by the failure path has elapsed, and the claim is what enforces that. Implementations MUST NOT select failed rows with a read that ignores the floor: doing so republishes a message the same drain has just deferred, on every poll cycle, which is the zero-backoff retry loop the floor exists to prevent.
As with PublishScheduledMessagesAsync(CancellationToken), this is a further pass of the same claim-backed
drain and may deliver messages of any category. maxRetries is validated but does not
narrow the batch; the retry ceiling is enforced by the dead-letter transition, not by the drain.
Exceptions
- ArgumentOutOfRangeException
Thrown when maxRetries is less than 0.
- OperationCanceledException
Thrown when the operation is cancelled.