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!