Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should the DbContext in EF have a short life span?

I have a few long running tasks on my server. Basically they are like scheduled tasks - they run from time to time.

They all required access to the DB and I use Entity Framework for that. Each task uses a DbContext for access.

Should the DbContext object be recreated on every run or should I reuse it?

like image 885
Daron V Avatar asked Sep 22 '13 19:09

Daron V


2 Answers

I should say "it depends" as there are probably scenarios where both answers are valid, however the most reasonable answer is "the context should be disposed as soon as it is not needed" which in practice means "dispose rather sooner than later".

The risk that comes from such answer is that newcomers sometimes conclude that the context should be disposed as otfen as possible which sometimes lead to a code I review where there are consecutive "usings" that create a context, use it for one or two operations, dispose and then another context comes up next line. This is of course not recommended also.

In case of web apps, the natural lifecycle is connected with a lifecycle of web requests. In case of system services / other long running applications one of lifecycle strategies is "per business process instance" / "per usecase instance" where business processing / use case implementations define natural borders where separate instances of contexts make sense.

like image 135
Wiktor Zychla Avatar answered Oct 21 '22 08:10

Wiktor Zychla


Yes, DbContext should only live for a very short time. It is effectively your unit of work

You should definitely create it each time you're going to use it. (Well, you should inject it but that's another discussion :-))


Update : OK, I accept that 'create it each time you're going to use it' could be misleading. I'm so used to context being an instance on a class that is injected and so lives only for the life of a request that I struggle to think of it any other way... @wiktor's answer is definitely better as it more correctly expresses the idea that you should "dispose sooner rather than later"

like image 24
Paul D'Ambra Avatar answered Oct 21 '22 07:10

Paul D'Ambra