Context in EF is, in essence, a ready implementation of several patterns at once:
The last two significantly limit the possible options for the lifetime of the context:
Unit of work
The concept of concurrency problems.
Identity map
It keeps track of all the single business transaction . Whenever you want it, you can’t.
From the two quotes above it follows directly that the context should live exactly one business transaction:
- If he lives less (“produce contexts” in the question) - then part of the operation code will not see the changes made before it.
- If he lives longer, for several operations - then other operations will see irrelevant data (due to the Identity Map) or vice versa, we will see changes that have not yet been saved.
What is a business transaction (business transaction) - depends on the specific subject area. This is not a transaction in terms of databases, but a broader concept - a kind of holistic action in terms of the subject area.
Usually it is a call to the service / facade code in BL - DoWork
, where Work is some kind of integral operation, action. Those. this is usually the top level function call in your application.
Considerations of memory usage, thread safety, cost of creation, synchronization with the database are completely secondary, and should not be the basis for choosing the context lifetime.
Context is an attempt to reflect in the code a complete operation from the subject area. It doesn’t matter to the domain whether you do it in one thread or in different ones, spend a lot of memory or a little, do you have to write huge methods, or manage a couple of lines - this doesn’t affect the integrity of the operation. Accordingly, the choice of the lifetime of the context should not affect.
The choice of the container in the code within which the contextt lives - the function, the form, the flow, the query, the application - is also secondary. It should be the effect, not the cause, of the lifetime of the context.
- If a particular function (
DoWork
) corresponds to a business transaction, it must control the lifetime of the context. If not ( DoWork2
) - then no. - If a business operation is stretched to the time the form is displayed, then the lifetime of the context must coincide with the form, and the context may well be the field of the form. If not, then no.
- If you run a background operation in a separate thread, then the lifetime will most likely coincide with the lifetime of the stream. But not because it is a background operation, but because it is a background operation .
- If you have a console application that performs exactly one business operation, then it is reasonable to use one context per application.