One DbContext per web request… why?

后端 未结 9 1390
死守一世寂寞
死守一世寂寞 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:54

    Another understated reason for not using a singleton DbContext, even in a single threaded single user application, is because of the identity map pattern it uses. It means that every time you retrieve data using query or by id, it will keep the retrieved entity instances in cache. The next time you retrieve the same entity, it will give you the cached instance of the entity, if available, with any modifications you have done in the same session. This is necessary so the SaveChanges method does not end up with multiple different entity instances of the same database record(s); otherwise, the context would have to somehow merge the data from all those entity instances.

    The reason that is a problem is a singleton DbContext can become a time bomb that could eventually cache the whole database + the overhead of .NET objects in memory.

    There are ways around this behavior by only using Linq queries with the .NoTracking() extension method. Also these days PCs have a lot of RAM. But usually that is not the desired behavior.

提交回复
热议问题