Click here to Skip to main content
15,076,465 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I am using unit of work pattern for EF core database first approach in my application.
I have also implemented database transactions in unit of work class.
For e.g.
C#
public class UnitOfWork : IUnitOfWork
{
    private myDBContext _dBContext;
    public IDatabaseTransaction BeginTransaction()
    {
        return new EntityDatabaseTransaction(_dBContext);
    }
}

Now I have handlers for different operations and each handler have dependency injection of unit of work. Inside handlers I am using transactions for DB operation.
For e.g.
C#
public class Operation1Handler : BaseHandler
{
    IUnitOfWork _unitOfWork;
    public Operation1Handler(IUnitOfWork unitOfWork)
    {
        _unitOfWork = unitOfWork;
    }

    public override void Handle()
    {
        using(var _trans = _unitOfWork.BeginTransaction())
        {
            //some code
            _unitOfWork.Entity.SaveAsync();
            _trans.Commit();
        }
    }
}

Now this handler is getting called in a WebAPI method like
C#
public void MyAPI()
{
    var handler = new Operation1Handler();
    handler.Handle();
}


So far this is working perfectly fine.
Now my problem is I have to call 2 different handlers in a WebAPI method which will do different DB operations. But I want all operations under both handlers to be transaction compliant i.e. if operation of handler 2 fails, operation of handler 1 should also rollback.
C#
public void MyAPI()
{
    var handler = new Operation1Handler();
    handler.Handle();

    var handler2 = new Operation2Handler();
    handler2.Handle();
}

Can anyone help me to achieve this.

What I have tried:

I read about distributed transaction using transaction scope but not sure whether it will work in this case since it'll require DbContext changes.
Posted
Updated 14-Oct-19 3:40am
v3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900