Search code examples
c#asp.netdependency-injectionninject

Ninject InRequestScope() vs InThreadScope()


What the difference between them ? InRequestScope relies on HttpContext.Current which is available only from request thread, so is it different from InThreadScope ?


Solution

  • If you declare a binding InThreadScope when you expect your objects to live in the context of the HttpRequest, you will encounter many issues :

    • phantom objects : a thread will be used to serve many requests. Some objects which were instantiated when the thread started to serve its first request will be reused over and over in the contexts of other requests, where you would expect to have new objects instantiated
    • object leaks : some objects like SqlConnections which must be disposed at the end of the request will not be disposed anymore until the thread is recycled, which you have no control on
    • random context switches : async/await operations often mean thread switching. This will lead to unexpected behaviours as factories may return different object before and after the await operation

    You should not not use InThreadScope in the context of an HttpRequest, as you should not use the ThreadStatic attribute in this same context