Sql Server Transaction Middleware Edit on GitHub


You can use the [SqlTransaction] attribute on message (or HTTP) handler methods to wrap the message handling inside a single Sql Server transaction like so:


public class ItemCreatedHandler
{
    [SqlTransaction]
    public static async Task Handle(
        ItemCreated created,
        SqlConnection conn,      // the connection for the container scope
        SqlTransaction tx,       // the current transaction
        MessageTracker tracker,
        Envelope envelope)
    {
        await conn.CreateCommand(tx, "insert into receiver.item_created (id, name) values (@id, @name)")
            .With("id", created.Id)
            .With("name", created.Name)
            .ExecuteNonQueryAsync();

        tracker.Record(created, envelope);
    }
}

When you use this middleware, be sure to pull in the current SqlTransaction object as a parameter to your handler method.