using MediatR; using Microsoft.Extensions.Logging; using System.Transactions; using ZeroFramework.EventBus.Extensions; namespace ZeroFramework.DeviceCenter.Application.Behaviors { public class TransactionBehavior(ILogger> logger) : IPipelineBehavior where TRequest : IRequest { private readonly ILogger> _logger = logger ?? throw new ArgumentException(nameof(ILogger)); public async Task Handle(TRequest request, RequestHandlerDelegate next, CancellationToken cancellationToken) { string? typeName = request?.GetGenericTypeName(); TResponse? response = default; using (TransactionScope? scope = new(TransactionScopeOption.Required, new TransactionOptions { IsolationLevel = IsolationLevel.ReadCommitted })) { try { response = await next(); scope.Complete(); } catch (Exception ex) { _logger.LogError(ex, "ERROR Handling transaction for {CommandName} ({@Command})", typeName, request); throw; } } return response; } } }