Sensible defaults for .NET transactions.
Transactions in .NET provide a lot of awesomeness. However, the default
construction of TransactionScope
is broken.
Enable.Transactions
provides a wrapper around TransactionScope
that
ensures that transactions are generated with sensible default options.
What's really neat, is that by using this library, your use of transactions
can easily be unit tested!
In order to avoid being bitten by TransactionScope
's nasty default settings,
replace any use of new TransactionScope()
with the following:
var factory = new TransactionScopeFactory();
using (var transaction = factory.CreateTransactionScope())
{
// Do your clever work here.
transaction.Complete();
}
Behind the scenes, this creates a TransactionScope
with the following properties:
TransactionScopeOption
=TransactionScopeOption.Required
TransactionOptions.IsolationLevel
=IsolationLevel.ReadCommitted
TransactionOptions.Timeout
=TransactionManager.DefaultTimeout
TransactionScopeAsyncFlowOption
=TransactionScopeAsyncFlowOption.Enabled
If the default options provided by
TransactionScopeFactory.CreateTransactionScope()
are not quite what you'd
like, these can be adjusted.
In the following example, we override the default timeout, increasing this to 5 minutes.
var factory = new TransactionScopeFactory();
var options = new TransactionScopeOptions
{
ScopeTimeout = TimeSpan.FromMinutes(5)
};
using (var transaction = factory.CreateTransactionScope(options))
{
// Do some lengthy work here.
transaction.Complete();
}
TransactionScopeFactory
implements the interface
ITransactionScopeFactory
.
The transaction scope returned by the CreateTransactionScope
method on this
interface in turn implements the interface
ITransactionScope
. This makes
it a breeze to mock transactions in tests, and to use TransactionScopeFactory
with your favourite Dependency Injection framework.