title: AutoFac Delegate Factories and the Lifetime Scope
body: <p>I'm using delegate Factories in my application. Thats because the components I create with AutoFac use Service classes that need some Parameter. </p>
  
  <p>The next Thing I wanted to do is caring that these services are cleaned up correctly and resources are released using AutoFacs lifetime scope mechanism. The Problem however is that when I create the components using the delegate factories they seem not to be put into the lifetime scope and Dispose is not called after disposing the lifetime scope.</p>
  
  <p>I want to avoid the generic Owned&lt;> because I dont want to bind my application to a specific IOC.</p>
  
  <p>In <a href="http://nblumhardt.com/2011/01/an-autofac-lifetime-primer/" rel="noreferrer">http://nblumhardt.com/2011/01/an-autofac-lifetime-primer/</a> it is explained that the created components by a delegate factory are put into the same lifetime scope as the delegate factory.</p>
  
  <p>I wrote a small Programm to demonstrate this. In this Program I would expect that the Dispose function is called. Unfortunatley this doesnt happen. Do I miss here sth? Anything wrong with the code below? How can I assure that components produced by the delegate factory are put into the life time scope of the delegate factory?</p>
  
  <pre><code>using Autofac;
  using Autofac.Core;
  using System;
  
  namespace FactoryTest
  {
  class Component : IDisposable
  {
      public Component(int i) { }
  
      public void Dispose()
      {
          throw new NotImplementedException();
      }
  }
  
  class Program
  {
      static void Main(string[] args)
      {
          var builder = new ContainerBuilder();
  
          builder.Register&lt;Func&lt;int, Component&gt;&gt;(c =&gt; (x) =&gt;
          {
              // code that is important and that should run
              // inside the delegate factory.
              return new Component(x);
              });
  
          IContainer root = builder.Build();
  
          using (ILifetimeScope lf = root.BeginLifetimeScope())
          {
              Func&lt;int, Component&gt; compDelegatefac = lf.Resolve&lt;Func&lt;int, Component&gt;&gt;();
              Component cmp = compDelegatefac(2);
          }
      }
  }
  }
  </code></pre>