C
C#15mo ago
Messiah

❔ Singleton/semaphor EF Core

I need to make sure only one instance of EF Core (db context) runs at once, otherwise if two requests arrive at the same time, they'll both search for the username in the DB, see that they don't exist and try to create them, instead of redirecting the second request to a login logic. How can something like this be accomplished? There's a billion different ways to implement this and I'm not entirely sure which one is the best/simplest for my use case. There's blocking collection, dictionaries, semaphores, semaphoreSlim, queues, concurrentqueues, list goes on.
8 Replies
JakenVeina
JakenVeina15mo ago
I need to make sure only one instance of EF Core (db context) runs at once
No, you need to implement concurrency the most naive implementation would be to wrap a transaction around all of your database operations that involve writes, and set its IsolationLevel to Serializable a more sophisticated implementation would be to use IsolationLevel.Snapshot and recover from failed commits by handling the exceptions thrown
JakenVeina
JakenVeina15mo ago
Handling Concurrency Conflicts - EF Core
Managing conflicts when the same data is updated concurrently with Entity Framework Core
Messiah
MessiahOP15mo ago
thank you! never heard about these implementations before
Omnissiah
Omnissiah15mo ago
there other ways too, for example all requests to db could be put in a queue so that they are executed one at a time
JakenVeina
JakenVeina15mo ago
that's precisely what IsolationLevel.Serializable does
Pobiega
Pobiega15mo ago
is it? Doesn't that make the DB actually lock the individual rows for both read and write operations, potentially creating deadlocks?
JakenVeina
JakenVeina15mo ago
possibly you could just as easily deadlock with a literal queue implementation
Accord
Accord15mo ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.
Want results from more Discord servers?
Add your server