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.
IDbConnectionlikeDbConnectionWithNestedTransactionSupportwhich returnsNestableDbTransactionwhenBeginTransactionis called (the same if called multiple times and the current transaction is pending). TheNestableDbTransaction : IDbTransactionwould only commit whenCommitis called the same number of times asBeginTransaction(would have a reference to the connection) orRollback. IfRollbackis called once then any furtherCommitcalls would be considered asRollback.applicationlayer that starts the transactions (application use case entry point) and delegate to abusinesslayer which would not handle transactions.