DbContext Disposed after first request when using Ninject's InRequestScope()

前端 未结 3 758
借酒劲吻你
借酒劲吻你 2021-02-10 06:17

I am new to both EF and Ninject so forgive me if this does not make sense :)

I have an MVC3 application with the Ninject and Ninject.Web.Common references. I am trying

3条回答
  •  被撕碎了的回忆
    2021-02-10 06:34

    I'd argue against putting DbContext in a RequestScope because according to the NInject documentation, RequestScope relies on HttpContext. That's not guaranteed to be disposed at the end of your request.

    I once experimented with putting DbContext in various object scopes, but always seemed to get inconsistent results.

    The Ninject kernel maintains a weak reference to scoping objects and will automatically Dispose of objects associated with a scoping object when the weak reference to it is no longer valid. Since InRequestScope() uses HttpContext.Current or OperationContext.Current as the scoping object, any associated objects created will not be destroyed until HttpContext.Current or OperationContext.Current is destroyed. Since IIS/ASP.NET manages the lifecycle of these objects, disposal of your objects is tied to whenever IIS/.NET decides to destroy them and that may not be predictable.

提交回复
热议问题