daramasala
daramasala

Reputation: 3030

Entity Framework's DbContext Lifetime in Worker Role

I have worker role that does some work with the database every second.

Is it ok to initialize the DbContext when the worker is started and use it throughout the lifetime of the worker?

How is the db connection handled? What if the database goes offline and back online? Will I still be able to use the context?

Upvotes: 5

Views: 1075

Answers (2)

Paul Carroll
Paul Carroll

Reputation: 1887

My advice is to create, use and destroy the context for each operation... do not hang onto it. I used to worry at first because I had no idea how expensive it was to create the DbContext, the answer is, not very.

If you attempt to keep reusing a DbContext instance you will also run into problems (very quickly) as it's internal state models will start reporting conflicts for versions of the object that have been loaded (updated whatever) previously

Upvotes: 2

daramasala
daramasala

Reputation: 3030

To my best current knowledge, the main DbContext abstraction is the unit of work.

DbContext opens and closes a db connection whenever it needs to (i.e. on context.SaveChanges()) so the db connection is irrelevant to the context's scope.

Looking at that this way, I now think that to decide what should be the scope of the DbContext instance you need to think of your unit of work and the entities it manages in memory.

For example, it my question, usually it will not make sense using a single context instance throughout the lifetime of the worker because:

  1. Usually you will work on different entities in each role invocation. In this case, the context will need to load these entities into memory anyway.

  2. Overtime, the context will manage more and more entities in memory which will cause performance problems (as it scans the graph looking for changes and things to do) and ultimately result in memory problems.

  3. Keeping entities in memory for a long time increases the chances of inconsistencies between the entities in the context and the actual data in the db. Resolving these inconsistencies can cost in performance.

To summarize, it is probably wrong to use the same DbContext instance throughout the lifetime of the worker role.

To decide on the scope of a DbContext think in terms of the unit of work you're implementing.

Upvotes: 2

Related Questions