In my best current knowledge, the main abstraction of DbContext is the unit of work.
DbContext opens and closes the db connection whenever it needs to (i.e., on context.SaveChanges() ), so the db connection is not related to the context area.
DbContext looked at this method, I now think that in order to make a decision on how DbContext instance should be, you need to think about your unit of work and the elements that it controls in memory.
For example, this is my question, it usually does not make sense using one instance of the context throughout the life cycle of the worker, because:
You will usually work with different objects in each role call. In this case, the context will still have to load these objects into memory.
Overtime context will manage a large number of objects in memory, which will cause performance problems (as it scans a graph that is looking for changes and doing something) and ultimately leads to memory problems.
Storing objects in memory for a long time increases the likelihood of inconsistencies between the objects in the context and the actual data in db. Resolving these inconsistencies can cost in performance.
To summarize, it is probably incorrect to use the same instance of DbContext throughout the life of a working role.
To determine the scope of a DbContext , think about the units of work that you implement.
source share