Short Version
How do i enlist in an ongoing TransactionScope?
Long Version
If you use a TransactionScope, you can create an "ambient" transaction:
using (TransactionScope scope = new TransactionScope())
{
//...stuff happens, then you complete...
// The Complete method commits the transaction.
scope.Complete();
}
What is that good for? Well, there are some classes in the .NET framework that know how to check if there is an ambient ongoing transaction by checking the static
:
This lets them know that there is a transaction in progress.
For example, if you had some arbitrary database operation that otherwise didn't consider transactions:
void DropStudents()
{
using (var cmd = connection.CreateCommand())
{
cmd.CommandText = "DROP TABLE Students;";
cmd.ExecuteNonQuery();
}
}
If you plop that in the middle of a TransactionScope:
using (TransactionScope scope = new TransactionScope())
{
DropStudents();
// The Complete method commits the transaction.
scope.Complete();
}
Suddnely your ADO.net operations are in a transaction; and can be rolled back.
Automatic BeginTranasction, Commit, and Rollback
The SqlClient library knows to check:
- System.Transactions.Current
and automatically internally:
- Begin a database transaction
- Commit the database transaction when you call Scope.Complete
- Rollback the database transaction when the scope is rolled back
And it's all just magic.
- somehow the
DbConnection
gets a notification to call.Commit
- and somehow the
DbConnection
gets a notification to call.Rollback
How do i do that?
I have a class that also has transactions. And rather than forcing the caller to call:
using (IContosoTransaction tx = turboEncabulator.BeginTransaction())
{
try
{
turboEncabulator.UpendCardinalGrammeters();
}
catch (Exception ex)
{
tx.Rollback();
throw;
}
tx.Commit();
}
It would be nice if they could just call:
turboEncabulator.UpendCardinalGrammeters();
And my code will simply check:
- System.Transactions.Current
And if there is a transaction in progress, i will:
- begin a transaction
- wait for the notification to Commit
- or wait for the notification to Rollback
But how do i do that?
How do i register myself with an ongoing TransactionScope to get these notifications?