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:

using (var conn = new SqlConnection(Servers.SqlServerConnectionString))
    await conn.OpenAsync();

    var tx = conn.BeginTransaction();

    // "context" is an IMessageContext object
    await context.EnlistInTransaction(tx);

    await action(context);


    await context.SendAllQueuedOutgoingMessages();

If you use the [Transaction] 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};