rebus-org / Rebus.SqlServer

:bus: Microsoft SQL Server transport and persistence for Rebus
https://mookid.dk/category/rebus
Other
43 stars 42 forks source link

Retrieve connection and transaction from IDbConnection #66

Closed Rensvind closed 4 years ago

Rensvind commented 4 years ago

Hi!

I was looking at the SqlAllTheWay sample since I wanted to make sure that rebus and my data persistence would share the same db connection/transaction. Looking at IDbConnection I saw that there is a CreateCommand method. Is there a reason for just exposing CreateCommand and not SqlConnection and SqlTransaction? I guess I can get the connection and transaction from the SqlCommand but that seems a bit strange to do.

mookid8000 commented 4 years ago

No other reason besides the fact that that made it convenient to use. 🙂

Rensvind commented 4 years ago

Is it ok if I make a pull request where I have exposed the SqlConnection and SqlTransaction in IDbConnection?

mookid8000 commented 4 years ago

While that sounds like a small and innocent contribution, it introduces a breaking change to the IDbConnection interface, requiring that the major version is bumped and any custom implementations out there be changed accordingly.

I'd do a lot to avoid that 🙂

I suggest you create an extension method like this:

    public static class RebusDbConnectionExtension
    {
        public static (SqlConnection, SqlTransaction) GetConnectionAndTransaction(this IDbConnection connection)
        {
            if (connection == null) throw new ArgumentNullException(nameof(connection));

            using var command = connection.CreateCommand();

            return (command.Connection, command.Transaction);
        }
    }

and then you can

var (sqlConnection, sqlTransaction) = dbConnection.GetConnectionAndTransaction();

wherever you need them...

I know it looks clunky, but that will avoid this breaking change for now. I'll consider introducing it the next time there's a breaking change to Rebus.SqlServer.