3

On my latest project, I thought it might be simpler to have only one context throughout the application. I notice that when I load a page that requires more then one query, it may return empty results.

For instance, I have a list of appointments and then a list of sales reps. They show up fine. Then I hit F5, sometimes all will keep being fine, but sometimes the appointment AND/OR rep list will be empty.

Is that a known issue with the single context apps? Is that design a bad one?

2
  • What is a "single context apps"? Commented Sep 11, 2012 at 0:57
  • It depends on how you implemented it. Can you show us an example? Commented Sep 11, 2012 at 1:18

1 Answer 1

6

Is that a known issue with the single context apps? Is that design a bad one?

I believe yes, with simple web application, you might not see the difference, but with complex web application with many users and required high con-currencies, the problems would be:

DbContext implements Unit Of Work pattern under the hood, with internal cache inside, so keeping global DbContext for long time would cause the memory leak and pull tons of data from database and keep them in memory (internal cache) for the time being.

Think about Unit Of Work is a business transaction, and internal cache in Unit Of Work is just for this transaction, not for global, if the transaction is done, Unit Of Work should be disposed asap.

The best practice for DbContext in web application is keeping lifetime of DbContext as per request. If you use IoC container, most of IoC Container supports per request lifetime management.

Sign up to request clarification or add additional context in comments.

3 Comments

+1 for DbContext per-request. One thing to add: DbContext is not thread safe. So, using the singleton instance of DbContext per AppDomain life-cycle is really bad if you don't know what u are doing.
@tugberk: what is the solution?
@Masoud use one DbContext instance per each request and dispose it on the way out.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.