Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do a code like 'TransactionScope' works?

Tags:

c#

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
}
like image 462
Only a Curious Mind Avatar asked Mar 17 '23 03:03

Only a Curious Mind


1 Answers

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.

like image 105
Jessica Avatar answered Mar 31 '23 21:03

Jessica