Ninject InThreadScope Binding

Posted by e36M3 on Stack Overflow See other posts from Stack Overflow or by e36M3
Published on 2010-12-23T13:24:55Z Indexed on 2010/12/23 15:54 UTC
Read the original article Hit count: 373

Filed under:
|
|
|
|

I have a Windows service that contains a file watcher that raises events when a file arrives. When an event is raised I will be using Ninject to create business layer objects that inside of them have a reference to an Entity Framework context which is also injected via Ninject. In my web applications I always used InRequestScope for the context, that way within one request all business layer objects work with the same Entity Framework context. In my current Windows service scenario, would it be sufficient to switch the Entity Framework context binding to a InThreadScope binding?

In theory when an event handler in the service triggers it's executed under some thread, then if another file arrives simultaneously it will be executing under a different thread. Therefore both events will not be sharing an Entity Framework context, in essence just like two different http requests on the web.

One thing that bothers me is the destruction of these thread scoped objects, when you look at the Ninject wiki:

.InThreadScope() - One instance of the type will be created per thread.
.InRequestScope() - One instance of the type will be created per web request, and will be destroyed when the request ends.

Based on this I understand that InRequestScope objects will be destroyed (garbage collected?) when (or at some point after) the request ends. This says nothing however on how InThreadScope objects are destroyed. To get back to my example, when the file watcher event handler method is completed, the thread goes away (back to the thread pool?) what happens to the InThreadScope-d objects that were injected?

EDIT: One thing is clear now, that when using InThreadScope() it will not destroy your object when the handler for the filewatcher exits. I was able to reproduce this by dropping many files in the folder and eventually I got the same thread id which resulted in the same exact Entity Framework context as before, so it's definitely not sufficient for my applications. In this case a file that came in 5 minutes later could be using a stale context that was assigned to the same thread before.

© Stack Overflow or respective owner

Related posts about c#

Related posts about .NET