MVFC.Outbox
6.0.0
dotnet add package MVFC.Outbox --version 6.0.0
NuGet\Install-Package MVFC.Outbox -Version 6.0.0
<PackageReference Include="MVFC.Outbox" Version="6.0.0" />
<PackageVersion Include="MVFC.Outbox" Version="6.0.0" />
<PackageReference Include="MVFC.Outbox" />
paket add MVFC.Outbox --version 6.0.0
#r "nuget: MVFC.Outbox, 6.0.0"
#:package MVFC.Outbox@6.0.0
#addin nuget:?package=MVFC.Outbox&version=6.0.0
#tool nuget:?package=MVFC.Outbox&version=6.0.0
MVFC.Outbox
Provides contracts and declarative DI builders to publish saved copies of entities (snapshots), schedule retries, manage messages through backoffice and run the Outbox worker.
Supports .NET 10 and .NET 11.
Built-in providers implement IOutboxExecutionPersistence. The worker uses independent slots, separate maintenance and the same execution flow in every dispatcher, including direct construction.
- Confirmation: retries saving the result without repeating delivery in the same reservation.
ConfirmationRetryAttemptsincludes the first attempt and also limits recovery from transient renewal failures. There is no delay after the final failure. - Shutdown: can confirm completed work within the drain deadline.
- Classifier failures: if
FailureClassifierthrows, logs the error and treats the original failure as transient. Lease, attempt limits and cancellation rules still apply. - Fixed leases: disabling renewal ignores
LeaseRenewalInterval; timeout and clock-margin validation still apply. - Custom providers: implement
IOutboxExecutionPersistenceto dispatch.ProducerOnlyrequires onlyIOutboxPersistence.
See the options reference and execution guide for cancellation and migration. Retention and native MongoDB TTL rules remain unchanged.
dotnet add package MVFC.Outbox
Basic and advanced configuration
Under Outbox, configure mode, destinations, parallelism, publication/handler timeouts, message retries and retention. See the basic appsettings and advanced reference.
The library calculates leases without an override and uses five slots when parallelism is null. Batch size limits admissions only for manual dispatch. Confirmation/renewal recovery uses its own backoff, independent of message retries.
Technical overrides live under Outbox:Advanced or outbox.Options.Advanced inside the AddOutbox callback:
outbox.Options.Advanced.ConfirmationTimeout = TimeSpan.FromSeconds(15);
outbox.Options.Advanced.LeaseDuration = null; // Uses automatic calculation.
Legacy properties forward to the same advanced object. Conflicting JSON paths are rejected; the builder runs after configuration. See the 5.0.0 behavior changes.
Namespaces
| Namespace | Main types |
|---|---|
MVFC.Outbox.Aggregates |
AggregateMapping, AggregateRegistry |
MVFC.Outbox.Configuration |
OutboxBuilder, OutboxOptions, OutboxMode |
MVFC.Outbox.Extensions |
AddOutbox, For/ForEach extensions |
MVFC.Outbox.Publishing |
IOutboxPublisher, OutboxMessageBuilder, OutboxReceipt, OutboxWriteState |
MVFC.Outbox.Messages |
OutboxMessage, OutboxStatus, OutboxDestinationKind |
MVFC.Outbox.Handlers |
IOutboxHandler<T>, OutboxHandlerContext<T> |
MVFC.Outbox.Persistence |
IOutboxPersistence, IOutboxExecutionPersistence, IOutboxSchemaInitializer |
MVFC.Outbox.Processing |
OutboxDispatcher, OutboxWorker, OutboxAdministration, RetryDelay |
MVFC.Outbox.Transport |
IOutboxTransport |
MVFC.Outbox.Diagnostics |
Internal generated logging declarations |
Configuration and usage
These example variables come from your application: services, configuration, connection, ct, order and topicId. Register services before building the host. Resolve IOutboxPublisher and your database context/session in the same dependency injection (DI) scope.
using MVFC.Outbox.Extensions;
using MVFC.Outbox.Handlers;
using MVFC.Outbox.MongoDB;
using MVFC.Outbox.MongoDB.Extensions;
using MVFC.Outbox.Publishing;
services.AddOutbox(configuration, outbox => outbox
.ProducerOnly()
.MapAggregate<Order, Guid>(order => order.Id, "order")
.UseMongoDB(mongo =>
{
mongo.ConnectionString = connection;
mongo.DatabaseName = "orders";
}));
var topicId = Guid.Parse("78214bd7-451a-4896-88be-08d7fcfdc32a");
await publisher.For(order).To(topicId).EnqueueAsync(ct);
await publisher.ForEach(orders).To(topicId).EnqueueAsync(ct);
Combine MVFC.Outbox with a persistence provider (the example above uses MVFC.Outbox.MongoDB). Configure Topics before calling .To(...) and HandlerRoutes before calling .ToHandler(...).
Multiple destinations, project override, and custom attributes
OutboxMessageBuilder is immutable: each configuration call returns a new builder. .To(...) and .ToHandler(...) accept params IEnumerable<Guid>:
using MVFC.Outbox.Extensions;
var createdTopic = Guid.Parse("78214bd7-451a-4896-88be-08d7fcfdc32a");
var auditedTopic = Guid.Parse("3b914e8e-e144-4f70-a520-e7d30dbe5bca");
await publisher.For(order)
.To(createdTopic, auditedTopic)
.WithProjectId("billing-project")
.WithAttributes(new Dictionary<string, string>
{
["source"] = "checkout",
["trace-id"] = "trace-123"
})
.WithPriority(1)
.EnqueueAsync(ct);
WithProjectId(string?)overrides the transport's default project for this operation (nullrestores the default).WithAttributes(...)copies the supplied dictionary (nullclears custom attributes). Keys must be nonempty, values cannot benull, and reserved library keys cannot be replaced:outbox-message-id,outbox-topic-id,aggregate-id,aggregate-type,schema-version.WithMessageIds(params Guid[])supplies explicit IDs (1 per generated message:entities × destinations), nonempty and distinct. When omitted,Guid.NewGuid()is generated per message.WithPriority(int)overrides message priority (default0).
Topics, routes, and transactional handlers
{
"Outbox": {
"Topics": {
"78214bd7-451a-4896-88be-08d7fcfdc32a": "orders-created",
"3b914e8e-e144-4f70-a520-e7d30dbe5bca": "orders-audited"
},
"HandlerRoutes": {
"a6d21ecc-9cd9-4486-8174-e7f3cae7acb8": "order"
}
}
}
using MVFC.Outbox.Extensions;
var routeId = Guid.Parse("a6d21ecc-9cd9-4486-8174-e7f3cae7acb8");
await publisher.For(order).ToHandler(routeId).EnqueueAsync(ct);
Register Handle<TMessage, THandler>() after MapAggregate in the consumer/worker process:
using MVFC.Outbox.Extensions;
using MVFC.Outbox.Handlers;
using MVFC.Outbox.MongoDB;
using MVFC.Outbox.MongoDB.Extensions;
services.AddOutbox(configuration, outbox => outbox.ConsumerProducer()
.MapAggregate<Order, Guid>(order => order.Id, "order")
.UseMongoDB(mongo =>
{
mongo.ConnectionString = connection;
mongo.DatabaseName = "orders";
})
.Handle<Order, ProcessOrderHandler>());
public sealed class ProcessOrderHandler : IOutboxHandler<Order>
{
public ValueTask HandleAsync(OutboxHandlerContext<Order> context, CancellationToken ct)
{
Console.WriteLine($"Handling {context.Message.Id}, message {context.MessageId}, attempt {context.Attempt}");
return ValueTask.CompletedTask;
}
}
public sealed record Order(Guid Id, decimal Total);
Each handler execution runs in its own DI scope and receives
Message,MessageId,RouteId,AggregateId,AggregateType,Attempt,ProjectIdandAttributes.Handlers must commit their effects before returning and honor
CancellationToken(HandlerTimeoutdefaults to30s; with renewal disabled, timeout plus confirmation must fit withinLeaseDuration).Delivery is at least once; persistent side effects require idempotency by
context.MessageId. See the complete transaction-idempotent example.Missing routes or handlers result in terminal errors (
IsTerminal = true), never Pub/Sub fallback.
Custom persistence and manual dispatch
Persistence means the component that saves and reads Outbox messages in the database. Register a custom provider with outbox.UsePersistence<MyPersistence>(). Built-in registrations such as UseMongoDB and UsePostgreSql already do this.
IOutboxPersistencedefines staging, acquisition, state transitions, administration and cleanup. It is sufficient forProducerOnly, which does not process messages.IOutboxExecutionPersistenceextends that contract with atomic lease renewal and untracked state reads. It is required to dispatch, even withEnableLeaseRenewal = false, because confirmation still reads durable state.ConsumerProducervalidates execution support during registration. Manual dispatch validates it when the dispatcher is resolved.
Resolve the dispatcher in a DI scope. The same execution, confirmation retries and shutdown rules apply to manual and automatic processing:
using Microsoft.Extensions.DependencyInjection;
using MVFC.Outbox.Processing;
await using var scope = host.Services.CreateAsyncScope(); // host is the built application host
var dispatcher = scope.ServiceProvider.GetRequiredService<OutboxDispatcher>();
var result = await dispatcher.DispatchAsync(cancellationToken: ct);
Version 4.0.0 replaces the previous Store names and removes its alternate execution path. Recompile consumers and follow the migration table. No database migration is required.
Backoffice administration
Use OutboxAdministration from DI to inspect errors and requeue messages after fixing their cause:
var errors = await administration.GetErrorsAsync(100, ct);
var requeued = await administration.RequeueAsync(messageId, ct);
RequeueAsync accepts Error records that have no active lease. It resets RetryCount, IsTerminal, scheduling, queue time and Error. It preserves identity, payload, destination kind, topic/route and priority.
Message record fields
EventType is the destination GUID; Attributes keeps attributes as JSON text; RetryCount counts persisted processing failures, including the first. Error stores the sanitized code. Aggregate IDs remain text to support different key types. See the 6.0.0 field migration.
| Field group | Purpose |
|---|---|
Id, EventType |
Stable message ID and logical destination GUID |
AggregateId, AggregateType, MessageType |
Entity identity and stable alias, independent of CLR assembly names |
DestinationKind |
Transport = 0 or Handler = 1; persists the choice without fallback |
ProjectId, Attributes |
Optional project for this publication and a saved JSON copy of custom attributes |
Payload, SchemaVersion |
Saved JSON copy of the entity and envelope schema version (currently 1) |
Status, RetryCount, IsTerminal, Error |
Numeric lifecycle (Pending = 0, Error = 1, Processed = 2), failure count and sanitized error classification |
Priority, CreatedAtUtc, QueuedAtUtc, NextAttemptAtUtc |
Selection order and retry scheduling with exponential delay and random variation (jitter) |
ClaimedAtUtc |
UTC time of the latest acquisition; starts null, survives renewal/completion and is cleared by administrative requeue |
LeaseToken, LeaseUntilUtc, Version |
Reservation ownership, lease validity and state version |
ProcessedAtUtc, ExpiresAtUtc |
Successful destination completion and processed-record retention |
Timeouts and shutdown
PublishTimeout and HandlerTimeout cancel only the message's token, independently of the worker's stopping token. A message timeout does not stop the worker. Before retrying a cancelled operation, its result must be saved with a valid lease.
During host shutdown, unconfirmed work remains recoverable after the lease expires.
The dispatcher waits for operations that have already started before leaving the processing window. This also applies when shutdown interrupts result confirmation. It stops reserving new messages when the host token is cancelled.
Completion still depends on the host's shutdown deadline and whether the process is forcibly terminated.
Cancellation is cooperative: handlers must pass the received token to their I/O operations. Wolverine's inline sender API cannot cancel a send that has already started, so the library waits for it to finish. Configure suitable timeouts in the transport client.
A timeout does not prove that an external effect failed or was rolled back. Use the stable message ID to make effects idempotent, so repeating a message does not repeat its effect. This is especially necessary when execution can outlast the lease.
Requirements
An application targeting .NET 10 or .NET 11.
A .NET host with dependency injection and a persistence provider. Configure a transport for topic publication or register typed handlers for local processing.
For development, use the .NET 11 SDK in global.json and .NET 10 targeting support. The playground and integration tests also require Docker. See the playground guide.
Contributing
See CONTRIBUTING.md for setup, Cake builds, tests and coverage conventions. Dependencies are listed in Directory.Packages.props.
License
Distributed under the Apache License 2.0. See LICENSE for all terms: permissions, redistribution conditions, and limits on warranty and liability.
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net10.0 is compatible. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. net11.0 is compatible. |
-
net10.0
- Microsoft.Extensions.Hosting (>= 10.0.15)
- Microsoft.Extensions.Options.ConfigurationExtensions (>= 10.0.15)
-
net11.0
- Microsoft.Extensions.Hosting (>= 11.0.0)
- Microsoft.Extensions.Options.ConfigurationExtensions (>= 11.0.0)
NuGet packages (3)
Showing the top 3 NuGet packages that depend on MVFC.Outbox:
| Package | Downloads |
|---|---|
|
MVFC.Outbox.EntityFrameworkCore
Shared EF Core model, transactional staging, conditional relational updates and versioned Outbox persistence. |
|
|
MVFC.Outbox.Wolverine
Confirmed Outbox publication through Wolverine's public inline transport senders. |
|
|
MVFC.Outbox.MongoDB
Native MongoDB Driver Outbox provider with transactional batches, atomic leases and TTL indexes. |
GitHub repositories
This package is not used by any popular GitHub repositories.