0

I have two methods which start sql transaction and commit (or rollback) the connection inside the method.

public void Method1(SqlConnection connection)
{
    var trans = connection.BeginTransaction();
    // do some work
    trans.Commit(); // or trans.Rollback(); 
}

public void Method2(SqlConnection connection)
{
    var trans = connection.BeginTransaction();
    // do some work
    trans.Commit(); // or trans.Rollback(); 
}

I have to create another method which executes logic of Method 1 and 2 but in a single transaction.

public void Method1And2(SqlConnection connection)
{
    var trans = connection.BeginTransaction();
    // do work of method 1
    // do work of method 2
    trans.Commit(); // or trans.Rollback(); 
}

Instead of duplicating code of method 1 and 2 inside Method1And2, I would like to call Method1 and Method2 from Method1And2 but still keeping a single db transaction. Method1 and Method2 will also require their own transaction if they are invoked directly.

What is the best approach to implement this in .Net?

Thanks.

developer
  • 1,401
  • 4
  • 28
  • 73
  • 1
    What about creating a wrapper that implements `IDbConnection` like `DbConnectionWithNestedTransactionSupport` which returns `NestableDbTransaction` when `BeginTransaction` is called (the same if called multiple times and the current transaction is pending). The `NestableDbTransaction : IDbTransaction` would only commit when `Commit` is called the same number of times as `BeginTransaction` (would have a reference to the connection) or `Rollback`. If `Rollback` is called once then any further `Commit` calls would be considered as `Rollback`. – plalx Apr 12 '17 at 01:55
  • Another and perhaps cleaner approach would be to have an `application` layer that starts the transactions (application use case entry point) and delegate to a `business` layer which would not handle transactions. – plalx Apr 12 '17 at 01:58

0 Answers0