Search code examples
unit-of-worktransactionscopeaspnetboilerplate

UnitOfWork: How to rollback and keep the logs


I have a method as below:

using (var unitOfWork = _unitOfWorkManager.Begin())
{
    var result = await ExcuteOperator(input);
    if (!result.WorkflowStatus) 
    {
        unitOfWork.Dispose();
    }
    unitOfWork.Complete();
}


public async Task<ExecuteOperatorOutput> ExcuteOperator(ExecuteOperatorInput input)
{                  
    //Doing something
    DoSomething(input);

    //Insert log
    await _logRepository.InsertAsync(logInput);

    //Recursive
    return await ExcuteOperator(input);
}

My question is: How to rollback the unitOfWork manually without throw exception before unitOfWork.Complete() and keep the inserted logs?


Solution

  • There is no way to rollback the unitOfWork manually.

    See rationale/attempts: https://github.com/aspnetboilerplate/aspnetboilerplate/issues?q=rollback

    That said, an interested reader is welcome to attempt and solve the issues.

    How to keep the logs after the transaction rolled back?

    Begin a new unitOfWork that gets completed:

    public async Task<ExecuteOperatorOutput> ExcuteOperator(ExecuteOperatorInput input)
    {                  
        //...
    
        using (var unitOfWork = _unitOfWorkManager.Begin(TransactionScopeOption.RequiresNew))
        {
            await _logRepository.InsertAsync(logInput);
            unitOfWork.Complete();
        }
    
        //...
    }