| | | 1 | | using Microsoft.Extensions.Logging; |
| | | 2 | | using NexMediator.Abstractions.Interfaces; |
| | | 3 | | |
| | | 4 | | namespace NexMediator.Pipeline.Behaviors; |
| | | 5 | | |
| | | 6 | | /// <summary> |
| | | 7 | | /// Pipeline behavior that handles transactions for commands only. |
| | | 8 | | /// </summary> |
| | | 9 | | /// <typeparam name="TRequest">The request type.</typeparam> |
| | | 10 | | /// <typeparam name="TResponse">The response type.</typeparam> |
| | | 11 | | public class TransactionBehavior<TRequest, TResponse> : INexPipelineBehavior<TRequest, TResponse> |
| | | 12 | | where TRequest : INexRequest<TResponse> |
| | | 13 | | { |
| | | 14 | | private readonly ITransactionManager _transactionManager; |
| | | 15 | | private readonly ILogger<TransactionBehavior<TRequest, TResponse>> _logger; |
| | | 16 | | |
| | 10 | 17 | | public TransactionBehavior( |
| | 10 | 18 | | ITransactionManager transactionManager, |
| | 10 | 19 | | ILogger<TransactionBehavior<TRequest, TResponse>> logger) |
| | 10 | 20 | | { |
| | 10 | 21 | | _transactionManager = transactionManager ?? throw new ArgumentNullException(nameof(transactionManager)); |
| | 9 | 22 | | _logger = logger ?? throw new ArgumentNullException(nameof(logger)); |
| | 8 | 23 | | } |
| | | 24 | | |
| | | 25 | | public async Task<TResponse> Handle(TRequest request, RequestHandlerDelegate<TResponse> next, CancellationToken canc |
| | 5 | 26 | | { |
| | | 27 | | |
| | 5 | 28 | | if (request is not INexCommand<TResponse>) |
| | 1 | 29 | | { |
| | 1 | 30 | | _logger.LogDebug("Skipping transaction for non-command request {RequestType}", typeof(TRequest).Name); |
| | 1 | 31 | | return await next(); |
| | | 32 | | } |
| | | 33 | | |
| | 4 | 34 | | await _transactionManager.BeginTransactionAsync(cancellationToken); |
| | | 35 | | |
| | | 36 | | try |
| | 4 | 37 | | { |
| | 4 | 38 | | _logger.LogDebug("Started transaction for command {RequestType}", typeof(TRequest).Name); |
| | | 39 | | |
| | 4 | 40 | | var response = await next(); |
| | | 41 | | |
| | 2 | 42 | | await _transactionManager.CommitTransactionAsync(cancellationToken); |
| | | 43 | | |
| | 2 | 44 | | _logger.LogDebug("Committed transaction for command {RequestType}", typeof(TRequest).Name); |
| | | 45 | | |
| | 2 | 46 | | return response; |
| | | 47 | | } |
| | 2 | 48 | | catch (Exception ex) |
| | 2 | 49 | | { |
| | 2 | 50 | | await _transactionManager.RollbackTransactionAsync(cancellationToken); |
| | | 51 | | |
| | 2 | 52 | | _logger.LogWarning(ex, "Rolled back transaction for command {RequestType} due to error", typeof(TRequest).Na |
| | | 53 | | |
| | 2 | 54 | | throw; |
| | | 55 | | } |
| | 3 | 56 | | } |
| | | 57 | | } |