asp.net mvc 4 - Okay to share DbContext per thread?

后端 未结 2 773
礼貌的吻别
礼貌的吻别 2021-02-06 12:03

From One DbContext per web request... why?

My understanding is that a DbContext instance should not be shared across concurrent web request, so definitely not across thr

2条回答
  •  迷失自我
    2021-02-06 12:20

    If you will use multiple DbContext per request you can end up with a multi threaded application with high possibility loosing data integrity. One web request can be viewed as one transaction ; but with PerThreadLifeTimeManager you would have multiple distinct transactions which aren't related but maybe they should. For example posting a form with many data can end up with saving multiple database table and with 2 or more independent context can happen that one insert succeeds but another fails and you could have inconsistent data.

    The other important thing is that the ASP.NET infrastructure uses thread pooling so every started thread will be reused after the request has finished and if something went wrong in one request it can affect another one. That is why not recommended to use any Thread-LocalStorage (static in the thread) in threadpool environment because we can not control the threads' lifetime.

提交回复
热议问题