Skip to content

This guide shows you how an Entity Framework Core application writes outbox rows and consumes inbox messages. Both sides follow one rule: the QueueBox row and the business write share one transaction on one connection.

QueueBox owns and migrates the outbox table. Map an entity to it, but do not generate a migration from the entity.

public class OutboxMessage
{
public Guid Id { get; set; }
public string Topic { get; set; } = default!;
public string? Key { get; set; }
public string Payload { get; set; } = default!;
public string Headers { get; set; } = "{}";
public string? AggregateType { get; set; }
}
public class OutboxMessageConfiguration : IEntityTypeConfiguration<OutboxMessage>
{
public void Configure(EntityTypeBuilder<OutboxMessage> builder)
{
builder.ToTable("outbox", t => t.ExcludeFromMigrations());
builder.Property(m => m.Id).HasColumnName("id");
builder.Property(m => m.Topic).HasColumnName("topic");
builder.Property(m => m.Key).HasColumnName("key");
builder.Property(m => m.Payload).HasColumnName("payload").HasColumnType("jsonb");
builder.Property(m => m.Headers).HasColumnName("headers").HasColumnType("jsonb");
builder.Property(m => m.AggregateType).HasColumnName("aggregate_type");
}
}
  • Name every column. The default convention does not turn AggregateType into aggregate_type.
  • Map only the columns that the application writes. The database fills state, attempt, scheduled_at, created_at, updated_at and sequence with their defaults. See the outbox table.
  • Set Headers to a JSON object string, never to null. The column is NOT NULL.

Add the business entity and the outbox row to one context, then call SaveChanges once. SaveChanges wraps both inserts in one transaction, so they commit together or not at all.

public async Task CreateOrder(ShopContext db, Guid orderId, string customerId, decimal amount, CancellationToken token)
{
db.Orders.Add(new Order { Id = orderId, CustomerId = customerId, Amount = amount });
db.OutboxMessages.Add(new OutboxMessage
{
Id = Guid.NewGuid(),
Topic = "order.created",
Key = customerId,
Payload = JsonSerializer.Serialize(new { orderId, amount }),
Headers = """{"X-Tenant":"acme"}""",
AggregateType = "order",
});
await db.SaveChangesAsync(token);
}

When the work needs more than one SaveChanges, open the transaction yourself with db.Database.BeginTransactionAsync and commit it after the last call.

Set Key to the ID of the thing whose messages must arrive in order, for example the customer or the order. QueueBox delivers the rows of one key in insert order, one at a time. See ordering.

A pull worker from QueueBox.Inbox.DependencyInjection claims inbox messages and gives each handler an open transaction. The handler writes through that transaction. The library completes the message in the same transaction and commits it. QueueBox.Inbox.EntityFrameworkCore holds InboxDbContextFactory.

Terminal window
dotnet add package QueueBox.Inbox.DependencyInjection
dotnet add package QueueBox.Inbox.EntityFrameworkCore

Versions before 0.5.0 ship InboxDbContextFactory in QueueBox.Inbox.DependencyInjection, with that namespace. From 0.5.0, add the second package and the second using below.

Build the context with InboxDbContextFactory.CreateOn. It hands the handler connection to your build delegate and enlists the context in the handler transaction.

using Npgsql;
using QueueBox.Inbox;
using QueueBox.Inbox.DependencyInjection;
using QueueBox.Inbox.EntityFrameworkCore;
var builder = Host.CreateApplicationBuilder(args);
builder.Services.AddSingleton<IInboxConnectionSource>(
InboxConnections.From(NpgsqlDataSource.Create(builder.Configuration.GetConnectionString("Queuebox"))));
builder.Services.AddQueueBoxInbox("payments", new InboxOptions { Source = "payments" }, async (message, transaction, token) =>
{
await using var db = InboxDbContextFactory.CreateOn(
transaction,
connection => new ShopContext(new DbContextOptionsBuilder<ShopContext>().UseNpgsql(connection).Options));
var orderId = message.Payload.GetProperty("orderId").GetGuid();
var order = await db.Orders.SingleAsync(o => o.Id == orderId, token);
order.PaidAt = DateTimeOffset.UtcNow;
await db.SaveChangesAsync(token);
});
await builder.Build().RunAsync();

The inbox source must use pull consumption. See Consume the inbox for the source configuration.

Follow these rules in a handler:

  1. Build every DbContext through InboxDbContextFactory.CreateOn. A context from dependency injection or from new opens its own connection. Its write then commits on its own, and a later failure makes QueueBox deliver the message again after the write already exists. Write outside the message transaction states when that trade is worth it.
  2. Do not call BeginTransaction, Commit or Rollback. The library owns the transaction.
  3. Throw to fail the message. The library rolls back every write of the handler.
  4. Pass the cancellation token on. It fires when the lease is lost.
  5. Make a call to another system safe to repeat. Deduplicate it on the source and the idempotency key.

InboxDbContextFactory references only Microsoft.EntityFrameworkCore.Relational. Add the provider package that your build delegate uses: Npgsql.EntityFrameworkCore.PostgreSQL or Microsoft.EntityFrameworkCore.SqlServer.

CreateOn must run in every handler, but its arguments do not change. Put the call on the context, once:

using System.Data.Common;
using Microsoft.EntityFrameworkCore;
using QueueBox.Inbox.EntityFrameworkCore;
public sealed class OrderContext(DbContextOptions<OrderContext> options) : DbContext(options)
{
public DbSet<Order> Orders => Set<Order>();
/// A context that writes in the transaction of the message.
public static OrderContext On(DbTransaction transaction) =>
InboxDbContextFactory.CreateOn(
transaction,
connection => new OrderContext(
new DbContextOptionsBuilder<OrderContext>().UseNpgsql(connection).Options));
}

A handler then needs one line:

await using var context = OrderContext.On(transaction);

On SQL Server, call UseSqlServer(connection) in place of UseNpgsql(connection).

The options of AddDbContext, which include its interceptors, do not apply to a context that CreateOn builds. Attach the configuration that every context needs, such as a soft delete interceptor, in OnConfiguring of the context or in its On method. An interceptor must not open its own connection or its own transaction, because its write then commits apart from the message.

A handler can be a method of a class that the container builds. This needs QueueBox.Inbox.DependencyInjection 0.4.0 or later.

using System.Data.Common;
using QueueBox.Inbox;
public sealed class OrderHandler(ILogger<OrderHandler> logger, TimeProvider clock)
{
public async Task HandleAsync(InboxMessage message, DbTransaction transaction, CancellationToken token)
{
await using var context = OrderContext.On(transaction);
context.Orders.Add(new Order { Id = message.Id, ReceivedAt = clock.GetUtcNow() });
await context.SaveChangesAsync(token);
logger.LogInformation("Stored order {Id}", message.Id);
}
}
builder.Services.AddSingleton<OrderHandler>();
builder.Services.AddQueueBoxInbox(
"orders",
new InboxOptions { Source = "orders" },
provider => provider.GetRequiredService<OrderHandler>().HandleAsync);

The factory runs once, on the root provider, so the worker keeps one OrderHandler for its whole life. Register the class as a singleton.

  • Build the context inside the method, with OrderContext.On. Do not take a DbContext through the constructor. A context from the container opens its own connection.
  • For a scoped service, take IServiceScopeFactory and open one scope for each message.

A handler can also ignore the message transaction, and write through its own context and its own transaction.

What you gain:

  • The application tables can live in another database than the inbox. The message transaction cannot reach that database, so this is the only pattern that works there.
  • The handler can open its own transactions. Npgsql refuses a second transaction on one connection, so code that calls BeginTransaction, such as a MediatR pipeline behaviour, cannot run on the message transaction.
  • The handler can use the DbContext that the container already registers, with its interceptors and its pooling.

What you lose:

  • The write and the completion no longer commit together. A message can take effect twice.
  • A throw no longer undoes the write. The library rolls back the message transaction only.
  • A lost lease no longer stops a write. The cancellation token fires, but a write that committed stays.

Make the handler idempotent before you use this pattern. Two ways work:

  • Record each handled message in your own table, keyed on the source and the idempotency key, in the same transaction as the write. Skip a message whose key is already there.
  • Make the write an upsert on a natural key, so a second run changes nothing.