I am using transactions in my unit tests to roll back changes. The unit test uses a dbcontext, and the service i\'m testing uses his own. Both of them are wrapped in one tra
Update: It seems this answer was unclear. It am not suggesting to keep DbContexts alive for as long as possible. Rather, use the Unit of Work pattern/idea. One context per UOW. Normally, this means one context per HTTP request, per GUI interaction or per test method. But it can be done differently if needed.
Using fresh contexts too frequently is an anti-pattern. Create one context and pass it around. It is very easy to do the passing around using a dependency injection framework.
Why not new contexts all the time? Because you want to be able to share entity object instances and pass them around. Other code can then modify them and at the end you call SaveChanges to persist everything atomically. This leads to very nice code.
However, if I close the outer dbcontext before calling the service and open a new dbcontext for the assert, everything works fine
No, this was a coincidence because the 2nd context reused the connection of the 1st from the connection pool. This is not guaranteed and will break under load.
The only way to avoid distributed transactions is to use one connection which has been kept open.
You can have multiple contexts sharing the same connection, though. Instantiate with a manually created connection to do that.