public async Task <TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate <TResponse> next) { var response = default(TResponse); var typeName = typeof(TRequest).Name; try { if (_context.HasActiveTransaction) { return(await next()); } var strategy = _context.Database.CreateExecutionStrategy(); await strategy.ExecuteAsync(async() => { Guid transactionId; using (var transaction = await _context.BeginTransactionAsync()) { _logger.LogInformation("----- Begin transaction {TransactionId} for {CommandName} ({@Command})", transaction.TransactionId, typeName, request); response = await next(); _logger.LogInformation("----- Commit transaction {TransactionId} for {CommandName}", transaction.TransactionId, typeName); await _context.CommitTransactionAsync(transaction); transactionId = transaction.TransactionId; } await _integrationEventService.PublishEventsThroughEventBusAsync(transactionId); }); return(response); } catch (Exception exception) { _logger.LogError(exception, "ERROR Handling transaction for {CommandName} ({@Command})", typeName, request); throw; } }
public async Task <TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate <TResponse> next) { var response = default(TResponse); var typeName = request.GetType().ToString(); try { var strategy = _dbContext.Database.CreateExecutionStrategy(); await strategy.ExecuteAsync(async() => { Guid transactionId; using (var transaction = await _dbContext.BeginTransactionAsync()) using (LogContext.PushProperty("TransactionContext", transaction.TransactionId)) { _logger.LogInformation("----- Begin transaction {TransactionId} for {CommandName} ({@Command})", transaction.TransactionId, typeName, request); response = await next(); _logger.LogInformation("----- Commit transaction {TransactionId} for {CommandName}", transaction.TransactionId, typeName); await _dbContext.CommitTransactionAsync(transaction); transactionId = transaction.TransactionId; } }); return(response); } catch (Exception ex) { _logger.LogError(ex, "ERROR Handling transaction for {CommandName} ({@Command})", typeName, request); _dbContext.RollbackTransaction(); throw; } }