title: Dependency injection in long-running Windows service - Composition root the right idea?
body: <p>I am writing a Windows Service that (if all goes according to plan) will run for months at a time. Throughout the lifetime of the service, it will maintain several WCF services (named pipes for communicating with other local apps), it will run an embedded data store (RavenDB probably, which is more or less irrelevant to this question), and it will use some third-party software to maintain a SIP service (VoIP functionality). Some of the challenges I am facing means having to react to events and create some new business objects to handle what these events represent.</p>
  
  <p>Now, I've read Mark Seemann's book (at least the relevant parts for this discussion), and I understand why a service locator is bad, and why handling this in the composition root (service starting point in my case) is good - in the general case.</p>
  
  <p>However, what I don't understand is how this can apply to every situation. I see how it would be perfect in the cases where you CAN compose your whole root at the start of the application, or in something like MVC where the IoC engine is used per request by the framework. However, for a long-running service, I imagine it would be inefficient in the best case, and impossible in some cases, to create all objects up front. I can't imagine being able to write a non-trivial service that gets all the objects it could ever need up front, and never need to create new ones as life goes on.</p>
  
  <p>Now, this isn't enough to lure me to the dark side and take on the expense of hidden dependencies like a service locator would have me do. But what is the right thing to do here? If I have a CallHandlerService that needs to be created in response to each incoming call (because it uses expensive, unmanaged resources for instance), how do I go about doing that? </p>
  
  <p>Composition root + just a wee bit of service locator?</p>
  
  <p>That last part wasn't serious, but I would still love to know how to solve this properly.</p>