Recommended life cycle for DbContext in ASP.NET web API?

Consider an ASP.NET Web API 2 application that provides fairly easy access to multiple DB tables using the Entity Framework.

Which of the following object lifecycles is best suited to serve most concurrent queries?

  • Create an instance of a single-line DbContext for use by all queries.
  • Create one DbContext for each incoming request.
  • Creating one DbContext for each thread in the thread pool serving inbound requests?
  • Other?

The next question. What if I change the requirement "require the least amount of database server resources"? What would be the best option then?

+5
source share
2 answers

Based on a detailed answer to another question:

Options 1 and 3 in my question are completely invalid. The reason is that DbContext is not thread safe and has access to multiple threads, which will lead to inconsistent data states and eliminate exceptions. Even in a “per-thread” situation, the ASP.NET Web API probably arbitrarily shifts the processing of a single request between multiple threads.

Option 2 - creating one DbContext for each incoming request is the preferred method because it ensures that only one thread at a time can access the DbContext.

+1
source

Besides thread insecurity, DbContexts should not live long. Therefore, you should use 2. (Or even one instance of DbContext for each Db operation).

If your “fairly easy access to multiple DB tables” is really simple, I would recommend that you use OData and some advanced js client like breeze.js.

Please look at the sites:

  • ASP.NET Web API OData Provides Data as a Simple REST Service
  • breeze.js this library provides extended js functionality similar to the function offered by DbContext, but from the browser side: syntax similar to LINQ, local (browser) data caching ...

You can also directly use the OData service (e.g. using jQuery AJAX) or with a simpler library (datajs, JayData)

0
source

Source: https://habr.com/ru/post/1201034/


All Articles