public Scope(TransactionScope instance, bool ownsInstance) { if (instance == null) throw new ArgumentNullException("instance"); _instance = instance; _ownsInstance = ownsInstance; Thread.BeginThreadAffinity(); _parent = _head; // If this is the Start of the outermost Scope, set SingleConnection to true. if (_head == null) { SingleConnection = true; ConnectionString = ""; connection = null; LastTransactionSuccess = true; Error = ""; } _head = this; }
public static Connection GetConnection(string connectionString) { if (Current != null) { // We are in an existing scope // First find if there is a connection already present with the same ConnectionString if (connection != null) { // We have a thread specific connection here, but find if it is using // the same connection string if (connectionString.Equals(connection.ConnectionString) && SingleConnection) { // We have a connection which we can use, so return it if (connection.State == ConnectionState.Closed) connection.Open(); return connection; } else { // There is already a connection in the current scope which is not // connecting to the same DB, so the transaction is going to be upgraded to // a full blown DTC. Hence all the connection from this point on may use their own instance SingleConnection = false; return CreateNewConnection(connectionString, false); } } else { // The existing connection is null, so we create a new connection, and maintain that // as our thread local connection connection = CreateNewConnection(connectionString, true); return connection; } } else { // We are not in an existing scope, so just create a new connection and give it back return CreateNewConnection(connectionString, false); } }
private static Connection CreateNewConnection(string connectionString, bool IsInTransaction) { Connection conn = new Connection(connectionString); conn.Open(); conn.InTransaction = IsInTransaction; return conn; }