Skip to content

Instantly share code, notes, and snippets.

@jeangatto
Created February 6, 2023 11:00
Show Gist options
  • Select an option

  • Save jeangatto/7844f64e3879786a71470f07ea62f5ef to your computer and use it in GitHub Desktop.

Select an option

Save jeangatto/7844f64e3879786a71470f07ea62f5ef to your computer and use it in GitHub Desktop.
ASP.NET Core EF Core Transaction Pipeline Behavior
public class TransactionBehaviour<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse>
where TRequest : IRequest<TResponse>
{
private readonly ITransaction _transaction;
public TransactionBehaviour(ITransaction transaction) => _transaction = transaction;
public async Task<TResponse> Handle(TRequest request, RequestHandlerDelegate<TResponse> next, CancellationToken cancellationToken)
{
var response = default(TResponse);
await _transaction.ExecuteAsync(
async () => response = await next(), cancellationToken);
return response;
}
}
public interface ITransaction
{
Task ExecuteAsync(Func<Task> operation, CancellationToken cancellationToken = default);
}
public class EfTransaction : ITransaction
{
private readonly ShopContext _context;
private readonly ILogger<EfTransaction> _logger;
public EfTransaction(ShopContext context, ILogger<EfTransaction> logger)
{
_context = context;
_logger = logger;
}
public async Task ExecuteAsync(Func<Task> operation, CancellationToken cancellationToken = default)
{
var strategy = _context.Database.CreateExecutionStrategy();
await strategy.ExecuteAsync(async () =>
{
using var transaction
= await _context.Database.BeginTransactionAsync(IsolationLevel.ReadCommitted, cancellationToken);
_logger.LogInformation("----- Begin transaction: '{TransactionId}'", transaction.TransactionId);
await operation();
try
{
var rowsAffected = await _context.SaveChangesAsync(cancellationToken);
_logger.LogInformation("----- Commit transaction: '{TransactionId}'", transaction.TransactionId);
await transaction.CommitAsync(cancellationToken);
_logger.LogInformation(
"----- Transaction successfully confirmed: '{TransactionId}', Rows Affected: {RowsAffected}",
rowsAffected, transaction.TransactionId);
}
catch (Exception ex)
{
_logger.LogError(
ex,
"An unexpected exception occurred while committing the transaction: '{TransactionId}', message: {Message}",
transaction.TransactionId, ex.Message);
await transaction.RollbackAsync(cancellationToken);
throw;
}
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment