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.
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.
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
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.
public void MyAPI()
{
var handler = new Operation1Handler();
handler.Handle();
var handler2 = new Operation2Handler();
handler2.Handle();
}
Can anyone help me to achieve this.
I think that when you are configuring your DI, IUnitOfWork lifetime should be Scoped. Use AddScoped method instead of AddTransient
I agree with @Rabban comment. Don't begin transactions manually