❔ 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
I need to make sure only one instance of EF Core (db context) runs at onceNo, 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 thrownHandling Concurrency Conflicts - EF Core
Managing conflicts when the same data is updated concurrently with Entity Framework Core
thank you! never heard about these implementations before
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
that's precisely what
IsolationLevel.Serializable
doesis it? Doesn't that make the DB actually lock the individual rows for both read and write operations, potentially creating deadlocks?
possibly
you could just as easily deadlock with a literal queue implementation
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.