Outbox Usage with Sql Server Edit on GitHub

See Jasper’s “Outbox” Pattern Support for more context around why you would care about the "outbox" pattern.

Jasper supports the "outbox" pattern with Sql Server connections. You can explicitly opt into this usage with code like this:

private static async Task outbox_sample(IMessageContext messaging, ItemCreated item)
    using (var conn = new SqlConnection(ConnectionSource.ConnectionString))
        await conn.OpenAsync();

        // Start your transaction
        var tx = conn.BeginTransaction();

        // enlist the current IMessageContext to persist
        // outgoing messages with the current transaction
        await messaging.EnlistInTransaction(tx);

        // enqueue outgoing messages
        await messaging.Send(item);


        // Flush the outgoing messages into Jasper's outgoing
        // sending loops, but don't worry, the messages are
        // persisted where they can be recovered by other nodes
        // in case something goes wrong here
        await messaging.SendAllQueuedOutgoingMessages();

If you use the [SqlTransaction] middleware in a message handler, the middleware will take care of some of the repetitive mechanics for you. In the code below, the IMessageContext is enrolled in the current transaction before the action runs, and the outgoing messages are flushed into the outgoing sending queue after the action runs.

public async Task<ItemCreatedEvent> Handle(CreateItemCommand command, SqlTransaction tx)
    var item = new Item {Name = command.Name};

    // persist the new Item with the
    // current transaction
    await persist(tx, item);

    return new ItemCreatedEvent {Item = item};

See also Outbox Pattern with Marten