One DbContext per web request… why?

后端 未结 9 1235
死守一世寂寞
死守一世寂寞 2020-11-21 22:09

I have been reading a lot of articles explaining how to set up Entity Framework\'s DbContext so that only one is created and used per HTTP web request using var

9条回答
  •  鱼传尺愫
    2020-11-21 22:46

    Not a single answer here actually answers the question. The OP did not ask about a singleton/per-application DbContext design, he asked about a per-(web)request design and what potential benefits could exist.

    I'll reference http://mehdi.me/ambient-dbcontext-in-ef6/ as Mehdi is a fantastic resource:

    Possible performance gains.

    Each DbContext instance maintains a first-level cache of all the entities its loads from the database. Whenever you query an entity by its primary key, the DbContext will first attempt to retrieve it from its first-level cache before defaulting to querying it from the database. Depending on your data query pattern, re-using the same DbContext across multiple sequential business transactions may result in a fewer database queries being made thanks to the DbContext first-level cache.

    It enables lazy-loading.

    If your services return persistent entities (as opposed to returning view models or other sorts of DTOs) and you'd like to take advantage of lazy-loading on those entities, the lifetime of the DbContext instance from which those entities were retrieved must extend beyond the scope of the business transaction. If the service method disposed the DbContext instance it used before returning, any attempt to lazy-load properties on the returned entities would fail (whether or not using lazy-loading is a good idea is a different debate altogether which we won't get into here). In our web application example, lazy-loading would typically be used in controller action methods on entities returned by a separate service layer. In that case, the DbContext instance that was used by the service method to load these entities would need to remain alive for the duration of the web request (or at the very least until the action method has completed).

    Keep in mind there are cons as well. That link contains many other resources to read on the subject.

    Just posting this in case someone else stumbles upon this question and doesn't get absorbed in answers that don't actually address the question.

提交回复
热议问题