MVFC.Outbox 4.1.0

There is a newer version of this package available.
See the version list below for details.
dotnet add package MVFC.Outbox --version 4.1.0
                    
NuGet\Install-Package MVFC.Outbox -Version 4.1.0
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="MVFC.Outbox" Version="4.1.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="MVFC.Outbox" Version="4.1.0" />
                    
Directory.Packages.props
<PackageReference Include="MVFC.Outbox" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add MVFC.Outbox --version 4.1.0
                    
#r "nuget: MVFC.Outbox, 4.1.0"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package MVFC.Outbox@4.1.0
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=MVFC.Outbox&version=4.1.0
                    
Install as a Cake Addin
#tool nuget:?package=MVFC.Outbox&version=4.1.0
                    
Install as a Cake Tool

MVFC.Outbox

🇧🇷 Leia em Português

CI codecov License Platform NuGet Version NuGet Downloads

Main guide · Playground

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. ConfirmationRetryAttempts includes 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 FailureClassifier throws, 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 IOutboxExecutionPersistence to dispatch. ProducerOnly requires only IOutboxPersistence.

See the options reference and execution guide for cancellation and migration. Retention and native MongoDB TTL rules remain unchanged.

dotnet add package MVFC.Outbox

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 (null restores the default).

  • WithAttributes(...) copies the supplied dictionary (null clears custom attributes). Keys must be nonempty, values cannot be null, 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 (default 0).

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, ProjectId and Attributes.

  • Handlers must commit their effects before returning and honor CancellationToken (HandlerTimeout defaults to 30s; with renewal disabled, timeout plus confirmation must fit within LeaseDuration).

  • 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.

  • IOutboxPersistence defines staging, acquisition, state transitions, administration and cleanup. It is sufficient for ProducerOnly, which does not process messages.
  • IOutboxExecutionPersistence extends that contract with atomic lease renewal and untracked state reads. It is required to dispatch, even with EnableLeaseRenewal = false, because confirmation still reads durable state.
  • ConsumerProducer validates 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 Attempts, IsTerminal, scheduling, queue time and LastErrorCode. It preserves identity, payload, destination kind, topic/route and priority.

Message record fields

Field group Purpose
Id, TopicId 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, AttributesJson 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, Attempts, IsTerminal, LastErrorCode 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)
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 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. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

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.

Version Downloads Last Updated
6.0.0 0 12/4/2026
5.0.0 70 12/3/2026
4.1.0 77 12/2/2026
4.0.0 108 12/1/2026
3.0.0 116 12/1/2026
2.0.1 155 11/30/2026
2.0.0 159 11/30/2026
1.1.1 167 11/30/2026
1.1.0 179 11/30/2026
1.0.1 163 11/30/2026
1.0.0 165 11/30/2026