C
C#4w ago
Thanacio

Dapper - Unit of work between 2 repositories

I need to keep a common transaction between 2 repositories, but I'm not sure who will be responsible for rolling it back in case of failure. Those 2 repositories do share connection and transaction via parent, but one of them has to commit the transaction. How do people usually go about this? - Do I make it so that the service is responsible for coordinating the repositories? I'm too new but this sounds wrong because a transaction commit/rollback is the responsibility of the database layer. - Do I call one repository method through another? This would mean injecting a repository, and I read that it's bad practice. Sorry, I'm new to Dapper and Unit of Work as a pattern.
12 Replies
taner.
taner.4w ago
When u have an service class then u usually commit all transactions after everything is done Can u share some code or give more details?
Thanacio
ThanacioOP4w ago
I can't because it's proprietary but I can approximate it. Basically, so far in the codebase, the unit of work is implemented like that (code not mine):
public async Task<int> CreateOrderAsync()
{
// UseTransaction begins the transaction that will get shared
UseTransaction(_connection.BeginTransaction());

try
{
// dapper stuff

foreach (var item in items)
{
// do stuff
}

// transaction gets commited at the end
_transaction.Commit();
return orderId;
}
catch
{
_transaction.Rollback();
throw;
}
}
public async Task<int> CreateOrderAsync()
{
// UseTransaction begins the transaction that will get shared
UseTransaction(_connection.BeginTransaction());

try
{
// dapper stuff

foreach (var item in items)
{
// do stuff
}

// transaction gets commited at the end
_transaction.Commit();
return orderId;
}
catch
{
_transaction.Rollback();
throw;
}
}
This is taken from the Dapper Repository I was wondering if lifting the Commit/Rollback responsibility to the service layer is a good/bad practice for it because right now the only place in our code responsible for commiting the ongoing transaction lives in repository methodss
taner.
taner.4w ago
I guess Unit of Work is what u r looking for
Thanacio
ThanacioOP4w ago
yes! ohhh I think I know where you're getting at making an intermediate class called UnitOfWork injecting it, then use it I think there is one in the codebase
taner.
taner.4w ago
Yeah this class injects normally the db context Where u commit ur changes etc
Thanacio
ThanacioOP4w ago
and is it used by the service?
taner.
taner.4w ago
Yeah
Thanacio
ThanacioOP4w ago
you're a lifesaver dude literally I'll keep you posted when I work it out 😄 brb
taner.
taner.4w ago
Yeah do it
Thanacio
ThanacioOP4w ago
alright, it's done! 😄 I even separated a concern to a new service thank you again for your help! probably saved my life
taner.
taner.4w ago
u r welcome
Thanacio
ThanacioOP3w ago
fwiw I think I had the right idea but ended up messing the execution and that cost me a job offer, but oh well 😐

Did you find this page helpful?