Chatter.MessageBrokers.Reliability.EntityFramework 0.8.0

There is a newer version of this package available.
See the version list below for details.
dotnet add package Chatter.MessageBrokers.Reliability.EntityFramework --version 0.8.0
                    
NuGet\Install-Package Chatter.MessageBrokers.Reliability.EntityFramework -Version 0.8.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="Chatter.MessageBrokers.Reliability.EntityFramework" Version="0.8.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Chatter.MessageBrokers.Reliability.EntityFramework" Version="0.8.0" />
                    
Directory.Packages.props
<PackageReference Include="Chatter.MessageBrokers.Reliability.EntityFramework" />
                    
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 Chatter.MessageBrokers.Reliability.EntityFramework --version 0.8.0
                    
#r "nuget: Chatter.MessageBrokers.Reliability.EntityFramework, 0.8.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 Chatter.MessageBrokers.Reliability.EntityFramework@0.8.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=Chatter.MessageBrokers.Reliability.EntityFramework&version=0.8.0
                    
Install as a Cake Addin
#tool nuget:?package=Chatter.MessageBrokers.Reliability.EntityFramework&version=0.8.0
                    
Install as a Cake Tool

<a name="chatter-reliability-entityframework"></a> Chatter.MessageBrokers.Reliability.EntityFramework

Durable EF Core inbox/outbox and unit-of-work for Chatter.MessageBrokers.

Overview

Chatter.MessageBrokers.Reliability.EntityFramework is the EF Core implementation of the reliability ports defined by Chatter.MessageBrokers: the brokered message inbox, outbox, and unit of work. Out of the box Chatter wires these ports to in-memory defaults; registering this package replaces those in-memory defaults with durable, relational storage backed by your application's DbContext.

This gives you:

  • Idempotent (once-only) message handling via a persisted inbox of processed message ids.
  • Reliable publish via the transactional outbox pattern — outgoing messages are written to your database in the same transaction as your domain state, then dispatched separately.
  • Atomic units of work that commit your domain changes and inbox/outbox writes together (or roll them all back) through a single EF transaction.

Because the inbox, outbox, and unit of work all run against the same DbContext, your business state and the messaging bookkeeping share one transaction and one commit.

Installation

dotnet add package Chatter.MessageBrokers.Reliability.EntityFramework

The package targets net8.0 and net10.0, and pulls in Microsoft.EntityFrameworkCore / Microsoft.EntityFrameworkCore.Relational for the matching framework.

Getting Started

Registration happens against the command pipeline builder, which Chatter exposes through the pipelineBuilder action on AddChatterCqrs(...) (the same IChatterBuilder you call AddMessageBrokers(...) on). Each extension method is generic over your DbContext type (TContext : DbContext).

public void ConfigureServices(IServiceCollection services)
{
    // Register your DbContext as usual.
    services.AddDbContext<MyDbContext>(opt =>
        opt.UseSqlServer(Configuration.GetConnectionString("Chatter")));

    services.AddChatterCqrs(Configuration, pipeline =>
            {
                // Replace the in-memory inbox with the durable EF inbox
                // (idempotent / once-only handling).
                pipeline.WithInboxBehavior<MyDbContext>();

                // Process the EF outbox for reliable publish.
                pipeline.WithOutboxProcessingBehavior<MyDbContext>();

                // Or, to opt into transactional units of work only:
                // pipeline.WithUnitOfWorkBehavior<MyDbContext>();
            })
            .AddMessageBrokers(/* message broker options */);
}

The available pipeline extension methods (Microsoft.Extensions.DependencyInjection.Extensions):

Method Effect
WithUnitOfWorkBehavior<TContext>() Replaces IUnitOfWork with the EF UnitOfWork<TContext> (scoped) and adds the UnitOfWorkBehavior.
WithInboxBehavior<TContext>() Adds the unit of work, replaces IBrokeredMessageInbox with BrokeredMessageInbox<TContext>, and adds the InboxBehavior.
WithOutboxProcessingBehavior<TContext>() Adds the OutboxProcessingBehavior, replaces IBrokeredMessageOutbox with BrokeredMessageOutbox<TContext> and IRouteBrokeredMessages with the outbox router, and adds the unit of work.

The order in which you call these methods does not affect the resolved pipeline order — see Reliability Behavior Order below.

Reliability Behavior Order

Regardless of which order you call WithInboxBehavior<TContext>(), WithOutboxProcessingBehavior<TContext>(), and WithUnitOfWorkBehavior<TContext>() — and no matter how many times you call them — the package always resolves the three reliability behaviors into the same nesting: outbox processing wraps the unit of work, which wraps the inbox.

  • The pipeline composes last-to-first, so the first-resolved behavior ends up outermost.
  • The inbox marker sits inside the unit of work so that, given the precondition below, it commits or rolls back together with the handler's work.
  • Outbox processing dispatches to the broker after the handler returns and must only dispatch committed rows, so it sits outside the unit of work.

This guarantee is independent of call order and call count — calling the extension methods in any sequence, or calling one of them more than once, always produces the same nesting. A behavior your application registers between the extension calls keeps the pipeline slot it was registered into, but may end up on a different side of the reliability behaviors than before.

Scope: this ordering guarantee covers only descriptors registered through WithUnitOfWorkBehavior<TContext>(), WithInboxBehavior<TContext>(), and WithOutboxProcessingBehavior<TContext>(). Later direct WithBehavior calls, and closed-generic, factory, keyed, or decorated registrations of these behavior types, are intentionally outside normalization and are not reordered.

Precondition (durability, not ordering): the ordering above is independent of TContext, but the commit-together guarantee is not. The guarantee holds whenever every reliability extension call names the same TContext, including a lone WithInboxBehavior<TContext>() call, which registers the matching unit of work itself. IUnitOfWork resolves to the TContext of the last call to any of WithUnitOfWorkBehavior<TContext>(), WithInboxBehavior<TContext>(), or WithOutboxProcessingBehavior<TContext>(); IBrokeredMessageInbox resolves to the TContext of the last WithInboxBehavior<TContext>(). It is void only when a later WithUnitOfWorkBehavior or WithOutboxProcessingBehavior call names a different TContext, leaving the unit of work committing a different DbContext than the one holding the marker.

Configuring the DbContext

The inbox and outbox entities — InboxMessage and OutboxMessage (from Chatter.MessageBrokers.Reliability.Inbox / .Outbox) — must be mapped onto your DbContext. This package ships IEntityTypeConfiguration<> classes for both. Apply them in OnModelCreating:

using Chatter.MessageBrokers.Reliability.EntityFramework;
using Chatter.MessageBrokers.Reliability.Inbox;
using Chatter.MessageBrokers.Reliability.Outbox;
using Microsoft.EntityFrameworkCore;

public class MyDbContext : DbContext
{
    public MyDbContext(DbContextOptions<MyDbContext> options) : base(options) { }

    // Your own aggregates / tables also live here.
    public DbSet<InboxMessage> InboxMessages { get; set; }
    public DbSet<OutboxMessage> OutboxMessages { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        modelBuilder.ApplyConfiguration(new InboxMessageConfiguration());
        modelBuilder.ApplyConfiguration(new OutboxMessageConfiguration());
    }
}

There is no separate "Chatter DbContext" — you supply your own, and the inbox/outbox tables live alongside your domain tables so they share the same transaction. Use EF migrations to create the tables.

Inbox & Outbox

Inbox (idempotency)

BrokeredMessageInbox<TContext> enforces once-only handling. When a message arrives, the inbox checks for its MessageId:

  • If the id is already present, the handler is skipped (the message was already processed).
  • Otherwise the handler runs, and on success an InboxMessage row is added recording the id and ReceivedByInboxAtUtc.

If the incoming message has no message id, the inbox simply executes the handler (no idempotency tracking is possible). The inbox add participates in the surrounding unit of work, so the handler's effects and the inbox record commit together — the inbox never saves on its own. This holds under the same-TContext precondition in Reliability Behavior Order.

Outbox (reliable publish)

BrokeredMessageOutbox<TContext> implements the transactional outbox. Outgoing messages are serialized and staged as OutboxMessage rows via SendToOutbox. Each row captures the serialized body, message context (JSON), destination, content type, send time, and a BatchId (the current transaction id). SendToOutbox participates in the surrounding unit of work, so the staged row and the work that produced it commit together — the outbox never saves on its own, and a message is never published unless the local state change commits. An enqueue with no surrounding unit of work is staged, not persisted. This holds under the same-TContext precondition in Reliability Behavior Order.

Processing then drains the outbox separately:

  • GetUnprocessedMessagesFromOutbox / GetUnprocessedBatch(batchId) return rows whose ProcessedFromOutboxAtUtc is null.
  • After a row is dispatched, UpdateProcessedDate stages the ProcessedFromOutboxAtUtc stamp. This column is an optimistic concurrency token, so two processors racing on the same row produce a DbUpdateConcurrencyException when the surrounding unit of work commits; the outbox's IUnitOfWork.ExecuteAsync, which wraps that commit, logs the time the winner recorded, resyncs the losing entry against the stored row, and rethrows. The token's guarantee is narrower than "exactly once": it prevents two stale, competing updates from both committing, so only one racer's stamp survives. It does not prevent a duplicate publish: OutboxProcessor dispatches the row to the broker before it stamps, so both racers have already published by the time either commit conflicts. Duplicate delivery is the accepted cost of this at-least-once drain, and handlers are expected to be idempotent.

Unit of Work / Persistance Transaction

UnitOfWork<TContext> coordinates a single atomic commit. Its ExecuteAsync runs your operation inside an EF execution strategy: it either begins a ReadCommitted transaction or participates in one already active on the context, runs the operation, and calls SaveChangesAsync, which flushes into whichever transaction is active regardless of who began it.

Commit and dispose are scoped to ownership, not merely to activity: ExecuteAsync commits and disposes only the transaction it began. If the caller opened the ambient transaction, the unit of work leaves it open on both the success path and the failure path — on failure the original exception propagates and it is the caller's own dispose that discards the work. A caller who opens their own transaction around dispatch must therefore commit or roll it back themselves; SQL Server holds locks for as long as they leave it open. That is the caller's choice, and the correct semantics for participating in someone else's unit of work.

If you have called EnableRetryOnFailure(...), you do not get participation — you get a throw. Opening your own transaction around dispatch and configuring a retrying execution strategy are mutually exclusive: EF's execution strategy rejects the combination with an InvalidOperationException before your operation runs, so ExecuteAsync never reaches the point where it would adopt your transaction. It rejects all three ways of having one — a transaction open on the DbContext, a transaction enlisted on it, and an ambient TransactionScope — and does so identically on net8.0 and net10.0. EF Core's default SQL Server strategy does not retry, so this affects only consumers who opted in. Chatter neither detects nor works around it; choose the retrying strategy or your own transaction, not both.

The transaction itself is exposed through IPersistanceTransaction, implemented by PersistanceTransaction, which wraps EF's IDbContextTransaction and surfaces TransactionId, CommitAsync, and RollbackAsync. The current transaction is also published into the TransactionContext container so the outbox can stamp each message's BatchId with the active transaction id.

Note: the type is intentionally spelled Persistance (and IPersistanceTransaction) in the codebase. The README uses the correct English spelling persistence in prose, but you must use Persistance when referencing the actual type.

Database Schema

The entity configurations map two tables (table names default to the DbSet/entity names unless you override them).

Inbox — InboxMessage

Column Type Constraints
MessageId string Primary key, required
ReceivedByInboxAtUtc DateTime? When the message was recorded in the inbox

Outbox — OutboxMessage

Column Type Constraints
Id int Primary key, required, generated on add (identity)
MessageId string Required
ProcessedFromOutboxAtUtc DateTime? Nullable; concurrency token; null until dispatched
SentToOutboxAtUtc DateTime Required
MessageBody string Required; serialized message payload
MessageContext string Required; JSON-serialized message context
MessageContentType string Required
Destination string Required
BatchId Guid Required; the transaction id the message was written under

Domain Language

See CONTEXT.md for the domain glossary (Brokered Message Inbox/Outbox, Unit of Work, Persistance Transaction).

← All Chatter modules

Product Compatible and additional computed target framework versions.
.NET net8.0 is compatible.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 was computed.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  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. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
0.12.1 138 9/24/2026
0.12.0 101 9/24/2026
0.11.0 116 9/23/2026
0.10.0 112 9/22/2026
0.9.0 127 9/20/2026
0.8.0 117 9/16/2026
0.7.0 115 9/15/2026
0.6.1 119 9/15/2026
0.6.0 133 9/2/2026
0.5.0 124 9/1/2026
0.4.2 174 6/16/2026
0.4.0 137 5/30/2026
0.3.1 4,252 12/30/2021
0.3.0 527 11/11/2021
0.2.1 594 6/5/2021
0.2.0 581 5/29/2021
0.1.1 772 1/29/2021
0.1.0 599 1/26/2021
0.0.7 652 11/30/2020
0.0.6 738 11/21/2020
Loading failed