How to chain requests in Mediatr12 with transactions

I am trying to implement a MediatR request pipeline for user registration following the CQRS principle. The scenario is as follows:

  • The CreateCompanyHandler will create a company or tenant, if this succeded, this handler will send another request to the CreateUserHandler
  • The CreateUserHandler will create an user object in the database with the companyId from the previous handler
  • After the user handler is finished, the GenerateActivationTokenHandler will be executed to generate the activation token, store it in the companie’s table and send an email to the customer

To ensure atomicity, I have created a PipelineBehaviour which should executed the database requests in one transaction:

    public async Task<TResponse> Handle(TRequest request, RequestHandlerDelegate<TResponse> next,
        CancellationToken cancellationToken)
    {
        if (IsNotCommand())
        {
            return await next();
        }

        var transactionOptions = new TransactionOptions
        {
            IsolationLevel = IsolationLevel.ReadCommitted,
            Timeout = TransactionManager.MaximumTimeout,
        };

        using var transactionScope = new TransactionScope(TransactionScopeOption.Required,
            transactionOptions,
            TransactionScopeAsyncFlowOption.Enabled);
        var response = await next();

        try
        {
            await unitOfWork.CommitChangesAsync(cancellationToken);
        }
        catch (Exception e)
        {
            logger.LogWarning("Cannot complete transaction: {Ex}", e);
        }

        transactionScope.Complete();
        return response;
    }

CreateCompanyHandler:

public class CreateCompanyHandler(
    IMediator mediator,
    ...)
    : BaseRequestHandler<CreateCompanyCommand, CreateCompanyRequestDTO, CreateCompanyResponse>(mediator)
{
   
    public override async Task<CreateCompanyResponse> Handle(CreateCompanyCommand request,
        CancellationToken cancellationToken)
    {
        await validator.ValidateAndThrowAsync(request.Dto, cancellationToken);
        var company = new Company
        {
           // ...
        };
        var companyFromDb = await companyRepository.AddAsync(company, cancellationToken);

        logger.LogInformation($"Company {company.CompanyNumber} successfully added.");
        var createUserRequestDto = new CreateUserRequestDTO
        {
          // ...
        };
        var response = await Mediator.Send(new CreateUserCommand(createUserRequestDto), cancellationToken);
        return !response.Success
            ? new CreateCompanyResponse(Result.Failure<CompanyDetailResponseDTO>(response.Exception, response.Error))
            : new CreateCompanyResponse(Result.Ok(MapToDto(companyFromDb)));
    }
}

In the GenerateActivationTokenHandler class, I fetch the newly created company from database and update the activationToken property:

public class GenerateActivationTokenHandler(
    IMediator mediator,
    ...)
    : BaseRequestHandler<GenerateActivationTokenCommand, GenerateActivationTokenRequestDto,
        GenerateActivationTokenResponse>(mediator)
{
    public override async Task<GenerateActivationTokenResponse> Handle(GenerateActivationTokenCommand request,
        CancellationToken cancellationToken)
    {
        await validator.ValidateAndThrowAsync(request.Dto, cancellationToken);

        var applicationUser = await userRepository.FindByIdAsync(request.Dto.UserId, cancellationToken);
        if (applicationUser == null)
        {
            return new GenerateActivationTokenResponse(
                Result.Failure<GenerateActivationTokenResponseDto>("No user found"));
        }

        var token = await userManager.GenerateEmailConfirmationTokenAsync(applicationUser);
        await StoreConfirmationTokenAsync(request.Dto.CompanyId, token, cancellationToken);
        var result = await SendConfirmAccountEmailAsync(applicationUser, token);

        return result
            ? new GenerateActivationTokenResponse(Result.Ok(new GenerateActivationTokenResponseDto(token)))
            : new GenerateActivationTokenResponse(
                Result.Failure<GenerateActivationTokenResponseDto>("Cannot send email."));
    }

   // ...

    private async Task StoreConfirmationTokenAsync(int companyId, string token, CancellationToken cancellationToken)
    {
        var company = await companyRepository.FindByIdAsync(companyId, cancellationToken);
        if (company == null) return;
        company.ActivationToken = token;
        await companyRepository.UpdateAsync(company, cancellationToken);
    }
}

However, each time I try to update the activationToken, I get the following exception:

System.InvalidOperationException: A second operation was started on this context instance before a previous operation completed. This is usually caused by different threads concurrently using the same instance of DbContext. For more information on how to avoid threading issues with DbContext, see https://go.microsoft.com/fwlink/?linkid=2097913.

Questions:

1.) Is it good practice to send commands within a RequesterHandler to reuse the code or are there any other best practices?

2.) How can I ensure atomicity using transactions with MediatR properly? For example, if an user with a given email address exist, the company should not be stored in the database.

Thanks for your input!

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật