Using EF to manipulate the database, extract the DbContext (database operation context class) in the same HTTP request to ensure uniqueness, the article uses two schemes to ensure the uniqueness of the Entity Framework context, and the solution on the .NET Core platform is attached.
Option 1
If an object is guaranteed to be globally unique, you will definitely think of a classic design pattern: singleton mode, if the object to be used must be unique in the thread?
Data slot: CallContext, ok see msdn's explanation of callcontent.
CallContext is a dedicated collection object similar to a thread-local store for method calls, and provides a data slot that is unique to each logical execution thread. Data slots are not shared between call contexts on other logical threads. Objects can be added to the CallContext when it propagates back and forth along the path of the execution code and is inspected by individual objects in that path.
That is, the current thread stores the object to the thread's local storage, and the object is destroyed as the thread is destroyed.
Use code:
Usage scenarios: I personally think it is used when the object needs to be used globally within the thread, and the other thread package extension threads cannot access it. For example, in EF's data context, a thread will be generated for each request, and at this time, a data context object will be created for different functions to use, and finally commit together to avoid transaction problems. Of course, some people may ask me if I can create a variable to use, which can also achieve the same purpose, of course, but this object can also interact with other thread data, which goes against the concept of being unique in the thread.
Option 2
The scenario is based on web http requests, because every request is a new thread, and the code is as follows:
Using "CallContext" in .NET Core
We know that CallContext is no longer available for . NETStandard or .NET Core.
But you can use Asynclocal<T> to mimic a CallContext, just create the following static class:
Namespaces that need to be referenced:
It's also easy to use (here I've put CallContext in the Common library):
|