rebus-org / Rebus.SqlServer

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

DbConnectionProvider does not open connection if enlistInAmbientTransaction = true #39

Closed karelg closed 5 years ago

karelg commented 5 years ago

I'm getting the following error, when configuring transport with enlistInAmbientTransaction = true:

Rebus.Injection.ResolutionException : Could not resolve Rebus.Transport.ITransport with decorator depth 0 - registrations: Rebus.Injection.Injectionist+Handler ----> System.InvalidOperationException : ExecuteReader requires an open and available Connection. The connection's current state is closed at Rebus.Injection.Injectionist.ResolutionContext.Get[TService]() at Rebus.Config.RebusConfigurer.<>c.b12_12(IResolutionContext c) at Rebus.Injection.Injectionist.ResolutionContext.Get[TService]() at Rebus.Config.RebusConfigurer.<>c__DisplayClass12_0.b25(IResolutionContext c) at Rebus.Injection.Injectionist.ResolutionContext.Get[TService]() at Rebus.Config.RebusConfigurer.<>c__DisplayClass12_0.b__26(IResolutionContext c) at Rebus.Injection.Injectionist.ResolutionContext.Get[TService]() at Rebus.Injection.Injectionist.Get[TService]() at Rebus.Config.RebusConfigurer.Start()

Looking at the source, I think the problem comes from DbConnectionProvider, where connection is opened only, if enlistInAmbientTransaction = false:

    private SqlConnection CreateSqlConnectionSuppressingAPossibleAmbientTransaction()
    {
      SqlConnection sqlConnection;
      using (new TransactionScope(TransactionScopeOption.Suppress))
      {
        sqlConnection = new SqlConnection(this._connectionString);
        sqlConnection.Open();  // Connection is opened here, if enlistInAmbientTransaction = false
      }
      return sqlConnection;
    }

    private SqlConnection CreateSqlConnectionInAPossiblyAmbientTransaction()
    {
      SqlConnection sqlConnection = new SqlConnection(this._connectionString);
      // Should also open connection here?
      Transaction current = Transaction.Current;
      if (current != (Transaction) null)
        sqlConnection.EnlistTransaction(current);
      return sqlConnection;
    }
thomasdc commented 5 years ago

I can also reproduce the issue.