Add Database Transactions in a Clean Architecture Project in .NET
This here is a clunky method but it does the job. If you have a better way of handling transactions in .net please do tell. I would love to avoid the UnitOfWork pattern; thank you.
Create a custom transaction manager interface and implement it
public interface ITransactionManager
{
Task ExecuteInTransactionAsync(Func<Task> operation);
Task<T> ExecuteInTransactionAsync<T>(Func<Task<T>> operation);
}
public class TransactionManager(ApplicationDbContext context) : ITransactionManager
{
public async Task ExecuteInTransactionAsync(Func<Task> operation)
{
using var transaction = await context.Database.BeginTransactionAsync();
try
{
await operation();
await transaction.CommitAsync();
}
catch
{
await transaction.RollbackAsync();
throw;
}
}
public async Task<T> ExecuteInTransactionAsync<T>(Func<Task<T>> operation)
{
using var transaction = await context.Database.BeginTransactionAsync();
try
{
var result = await operation();
await transaction.CommitAsync();
return result;
}
catch
{
await transaction.RollbackAsync();
throw;
}
}
}
Then register it for dependency injection in your DI container
services.AddScoped<ITransactionManager, TransactionManager>();
And just like that, transactions are back in the game!