Sql Server Transaction Middleware Edit on GitHub


Assuming that the Jasper.Persistence.SqlServer Nuget is referenced by your project, you can use the [Transactional] attribute on message (or HTTP) handler methods to wrap the message handling inside a single Sql Server transaction like so:


public class ItemCreatedHandler
{
    [Transactional]
    public static async Task Handle(
        ItemCreated created,
        SqlConnection conn, // the connection for the container scope
        SqlTransaction tx, // the current transaction
        Jasper.Messaging.Tracking.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.