title: Threaded Windows Service - Ninject Injected DbContext Instance Lifetime - Best Practice?
body: <p>I'm currently building a Windows Service which creates a thread which runs every 30 minutes and updates a few fields on some entities which meet a criteria (and in the future, I want to add further threads to do other things, eg run one every 24 hours, one every week, etc). The service will get and update it's data using services which are already used by a web application and are injected using Ninject (along with the DbContext) - this all works fine using the InRequestScope() binding.</p>
  
  <p>However, I've been thinking about how best to approach this using a Windows Service. Essentially, once the service starts and the thread is created, it runs continuously (aside from sleeping every 30 minutes) - and only ever stops if the Windows Service stops or the process gets terminated. My initial thought was to inject my DbContext and services using the InThreadScope() option of Ninject - so I'd have a DbContext for each thread. But is it generally good practice to have a DbContext that has such a long lifetime? This DbContext could be sitting there for weeks without being disposed - and I have a sneaking suspicion that this isn't such a a good idea (memory leaks, etc). </p>
  
  <p>But if not, what is the best way to handle this scenario. I could create a new DbContext each time the thread runs, but how would I set up the Ninject bindings? Currently they're defined as:</p>
  
  <pre><code>        Bind&lt;IDbContext&gt;().To&lt;EnterpriseDbContext&gt;().InThreadScope();
          Bind&lt;IUserRepository&gt;().To&lt;UserRepository&gt;().InThreadScope();
          // Etc
  </code></pre>
  
  <p>So I'm not entirely sure how I would structure this to create a new one within the thread. I looked at InTransientScope(), but this is causing my services to use different versions of the context, so my changes never get saved.</p>
  
  <p>This seems like it would be such a common scenario - so would be great to hear anyone else's view.</p>