title: Dependency Injection - What If Dependency Lifetimes Are Shorter Than The Dependent Object?
body: <p>I realise that DI is a very flexible design pattern, although I'm struggling to accept it as my 'silver bullet' for creating decoupled code.</p>
  
  <p><strong>Here's why:</strong> What happens when the dependent object has a longer lifetime than the dependencies it has been injected with?</p>
  
  <p><strong>Example application:</strong> I have a <code>BusinessLogic</code> class which is instantiated for the lifetime of my application. This class requires a <code>DataContext</code> object to perform database operations. I have thefore created an abstract <code>DataContextFactory</code> with two implementations: <code>StaticDataContextFactory</code> and <code>WebDataContextFactory</code>. The former maintains a single DataContext for the lifetime of the application, whereas the latter will create new DataContexts for each HTTP request.</p>
  
  <p><strong>Problem in the example :</strong> As you can see, all will be fine when the <code>StaticDataContextFactory</code> is used. However, when the <code>WebDataContextFactory</code> is used the <code>BusinessLogic</code> will fail, since it's injected with a <code>DataContext</code> which will expire/dispose once the first request completes.</p>
  
  <p><strong>My question is:</strong> Must all dependent objects have a lifetime which is less or equal to the lifetime of its dependencies? If so, then what happens when the lifetime of each dependency is unknown to the code which instantiates the dependent classes?</p>