using System.Data; using System.Text.Json; using MediatR; using Microsoft.Extensions.Logging; namespace BuildingBlocks.EFCore; public class EfIdentityTxBehavior : IPipelineBehavior where TRequest : notnull, IRequest where TResponse : notnull { private readonly ILogger> _logger; private readonly IDbContext _dbContextBase; public EfIdentityTxBehavior( ILogger> logger, IDbContext dbContextBase) { _logger = logger; _dbContextBase = dbContextBase; } public async Task Handle( TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate next) { _logger.LogInformation( "{Prefix} Handled command {MediatrRequest}", nameof(EfTxBehavior), typeof(TRequest).FullName); _logger.LogDebug( "{Prefix} Handled command {MediatrRequest} with content {RequestContent}", nameof(EfTxBehavior), typeof(TRequest).FullName, JsonSerializer.Serialize(request)); _logger.LogInformation( "{Prefix} Open the transaction for {MediatrRequest}", nameof(EfTxBehavior), typeof(TRequest).FullName); await _dbContextBase.BeginTransactionAsync(cancellationToken); try { var response = await next(); _logger.LogInformation( "{Prefix} Executed the {MediatrRequest} request", nameof(EfTxBehavior), typeof(TRequest).FullName); await _dbContextBase.CommitTransactionAsync(cancellationToken); return response; } catch { await _dbContextBase.RollbackTransactionAsync(cancellationToken); throw; } } }