Beispiel #1
0
        public async Task <TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate <TResponse> next)
        {
            var response = default(TResponse);
            var typeName = request.GetType().Name;

            try
            {
                if (_dbContext.HasActiveTransaction)
                {
                    return(await next());
                }

                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("Transaction started with {TransactionId} for {CommandName} ({@Command})",
                                                   transaction.TransactionId, typeName, request);

                            response = await next();

                            _logger.LogInformation("Transaction committed with {TransactionId} for {CommandName}",
                                                   transaction.TransactionId, typeName);

                            await _dbContext.CommitTransactionAsync(transaction);

                            transactionId = transaction.TransactionId;
                        }
                    }

                    await _integartionService.PublishEventsThroughEventBusAsync(transactionId);
                });

                return(response);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error in handling transaction for {CommandName} ({@Command})", typeName, request);

                throw;
            }
        }