One DbContext per web request… why?

后端 未结 9 1392
死守一世寂寞
死守一世寂寞 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条回答
  •  Happy的楠姐
    2020-11-21 22:50

    There are two contradicting recommendations by microsoft and many people use DbContexts in a completely divergent manner.

    1. One recommendation is to "Dispose DbContexts as soon as posible" because having a DbContext Alive occupies valuable resources like db connections etc....
    2. The other states that One DbContext per request is highly reccomended

    Those contradict to each other because if your Request is doing a lot of unrelated to the Db stuff , then your DbContext is kept for no reason. Thus it is waste to keep your DbContext alive while your request is just waiting for random stuff to get done...

    So many people who follow rule 1 have their DbContexts inside their "Repository pattern" and create a new Instance per Database Query so X*DbContext per Request

    They just get their data and dispose the context ASAP. This is considered by MANY people an acceptable practice. While this has the benefits of occupying your db resources for the minimum time it clearly sacrifices all the UnitOfWork and Caching candy EF has to offer.

    Keeping alive a single multipurpose instance of DbContext maximizes the benefits of Caching but since DbContext is not thread safe and each Web request runs on it's own thread, a DbContext per Request is the longest you can keep it.

    So EF's team recommendation about using 1 Db Context per request it's clearly based on the fact that in a Web Application a UnitOfWork most likely is going to be within one request and that request has one thread. So one DbContext per request is like the ideal benefit of UnitOfWork and Caching.

    But in many cases this is not true. I consider Logging a separate UnitOfWork thus having a new DbContext for Post-Request Logging in async threads is completely acceptable

    So Finally it turns down that a DbContext's lifetime is restricted to these two parameters. UnitOfWork and Thread

提交回复
热议问题