In addition to the transaction handling I already do inside the repository classes of my project (which is necessary because in some cases I need the ID of an inserted entity for another insert in the same repository function), I also want to be able to use transactions in my service layer. As my service layer is in a different project which has no references to EF Core, I therefore decided to write my own wrapper around the EF Core Database.BeginTransactionAsync()
Now I have the problem that there is a IDbContextTransaction
object returned when beginning a transaction, which I do not want to do in my wrapper because it would require adding a reference to EF Core in my service layer. How else could I design a class which allows me to use the EF Core transaction handling without the requirement of adding a reference to EF Core in my service layer? Are there any examples / common practices about this already which I could look into so I don't have to reinvent the wheel?
Asked
Active
Viewed 39 times
1

Gert Arnold
- 105,341
- 31
- 202
- 291

Chris
- 1,417
- 4
- 21
- 53
-
Just declare interface with BeginTransaction/... and interface for the return value in your service layer and do the implementations in your data access layer. This implementations then can wrap and make calls to the IDbContextTransaction and other EF objects. – Dusan Feb 02 '22 at 12:11
-
There is also other approach using `TransactionScope` which should work just fine with underlying EF. – Dusan Feb 02 '22 at 12:16
-
@Dusan I've been looking into the `TransactionScope` approach but I was told that `Database.BeginTransaction` should be preferred in most cases since it became available. Do you have an example for your suggestion to implement this with interfaces? – Chris Feb 02 '22 at 12:54