Created
June 13, 2024 06:34
-
-
Save admir-live/65108abed87a7a2d2b8141b9781e4955 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hello, please a example to use in a command or query