Skip to content

Instantly share code, notes, and snippets.

@admir-live
Created June 13, 2024 06:34
Show Gist options
  • Save admir-live/65108abed87a7a2d2b8141b9781e4955 to your computer and use it in GitHub Desktop.
Save admir-live/65108abed87a7a2d2b8141b9781e4955 to your computer and use it in GitHub Desktop.
using MediatR;
using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
public class TransactionBehavior<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse>
{
private readonly DbContext _dbContext;
public TransactionBehavior(DbContext dbContext)
{
_dbContext = dbContext ?? throw new ArgumentNullException(nameof(dbContext));
}
public async Task<TResponse> Handle(TRequest request, RequestHandlerDelegate<TResponse> next, CancellationToken cancellationToken)
{
// Check if the current request should be transactional
if (_dbContext.Database.CurrentTransaction != null)
{
return await next();
}
// Use a transaction to ensure all database operations are atomic
await using var transaction = await _dbContext.Database.BeginTransactionAsync(cancellationToken);
try
{
// Process the request
var response = await next();
// Commit the transaction if all operations succeed
await transaction.CommitAsync(cancellationToken);
return response;
}
catch (Exception)
{
// Roll back the transaction in case of an error
await transaction.RollbackAsync(cancellationToken);
throw;
}
}
}
@akiragothick
Copy link

Hello, please a example to use in a command or query

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment