Using TransactionScope
? Say goodbye to MSDTC!
If you are using Hangfire.SqlServer
storage and tried to place the BackgroundJob.Enqueue
method call inside a TransactionScope
transaction, you have probably noticed that the transaction is being escalated to the distributed one.
If you faced with the MSDTC on server 'XXX' is unavailable exception and turned on the Distributed Transaction Coordinator service, this post is for you either. You are not required to use slow distributed transactions and MSDTC service anymore.
To forget about distributed transactions, you should:
- Forget about using
BackgroundJob
class and start to useBackgroundJobClient
class instance for creating background jobs. - Pass an explicit instance of the
SqlConection
class to theSqlServerStorage
constructor. - Use the resulting storage in your
BackgroundJobClient
instance. - Do not use this constructor overload for
BackgroundJobServer
class!
using (var transaction = new TransactionScope())
{
using (var connection = new SqlConnection(connectionString))
{
connection.Open();
/* ... other SQL statements ... */
var storage = new SqlServerStorage(connection);
var client = new BackgroundJobClient(storage);
client.Enqueue(() => Console.WriteLine("MSDTC is not required for these lines!"));
}
transaction.Complete();
}
Release Notes
- Added – Ability to pass existing
SqlConnection
toSqlServerStorage
(#253). - Changed – Throw
NotSupportedException
for methods returningTask
(#255). - Fixed – Dashboard throws exception for deleted job in 1.2 (#254).
- Fixed – SqlServerStorage.ToString() uses case sensitive checks (#230).