I was reading about the transaction scope in C# and it works like this:
using (connectionDb)
{
connectionDb.Open();
using (var ts = new System.Transactions.TransactionScope())
{ <--
try
{
connectionDb.ExecuteNonQuery();
ts.Complete();
}
catch (Exception)
{
throw;
}
finally
{ }
} <--
}
Every clauses in the using brackets works at the same transaction, but I don't understand how the code identifies that the databasecommand are running on the scope without pass the transaction scope param neither the opening of the connection, and neither at the execution of the query.
For example, if i have the following code:
var myObject = new MyObject();
var childObject = new ChildObject();
childObject.Foo(myObject);
childObject.Bar(myObject);
Can I create a scope for the variable myObject
and use into the childObject methods without pass her by parameter? like this:
using(var myObject = new MyObject())
{
childObject.Foo(); -- Here the method use the variable myObject
childObject.Bar(); -- Here the method use the variable myObject
}
When you create a TransactionScope it is stored in the static variable Transaction.Current which is kept in thread local storage. The methods that interact with the transaction look at this variable to determine the transaction they are in. This is referred to as an ambient transaction.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With