title: Autofac Garbage Collection - BeginLifetimeScope
body: <p>I have created a windows service to build and send emails. I have implemented dependency injection and I'm using Autofac as the DI container. </p>
  
  <p>My problem is that as the service runs the allocated memory keeps growing, at the moment it is over 1GB. <a href="http://nblumhardt.com/2011/01/an-autofac-lifetime-primer/" rel="nofollow">I read this article about lifetimes</a>
  and from this I incorporated the BeginLifetimeScope, rather than resolving directly from the container. But this hasn't solved the problem. Any advice appreciated.</p>
  
  <p>Below is the Autofac configuration which is in my service onStart method.</p>
  
  <pre><code>ContainerBuilder builder = new ContainerBuilder();
  
  //Register the Database context
  builder.RegisterType&lt;DbContainer&gt;().As&lt;IDbContainer&gt;();
  
  //Register a single shared instance of Email Manager which will be shared by all EmailProcessing instances
  builder.Register(c =&gt; new EmailManager()).As&lt;IEmailManager&gt;()).SingleInstance();
  
  //Register email processing classes
  builder.Register(c =&gt; new EmailBuilder(c.Resolve&lt;IDbContainer&gt;(), c.Resolve&lt;IEmailManager&gt;())).As&lt;IEmailBuilder&gt;();
  
  _container = builder.Build();
  </code></pre>
  
  <p>Below is the email timer method which runs every 5 seconds.</p>
  
  <pre><code>private void EmailTimerElapsed(object sender, System.Timers.ElapsedEventArgs e)
  {
       using (var lifetime = _container.BeginLifetimeScope())
       {
            //Builder, and any of its disposable dependencies, will
            //be disposed of when the using block completes
            IEmailBuilder builder = lifetime.Resolve&lt;IEmailBuilder&gt;();
            //Execute the process emails method
            builder.ProcessEmails();
       }
  
       emailTimer.Start();
  }
  </code></pre>
  
  <p>I want the same instance of EmailManager to be used with every email timer iteration, but a new instance of everything else.</p>
  
  <p><strong>EDIT</strong></p>
  
  <p>Is there a way to check if EmailBuilder and all of its dependencies have been disposed and are ready for GC?</p>
  
  <p>A lot of my objects are going into Generation2 and are being held onto. Should they not be disposed when the lifetime has completed?</p>