title: Autofac Delegate Factories - How to create a new instance each time?
body: <p>Question: How do I use the Autofac Factory delegate to create a <em>new</em> instance while within an existing Autofac Lifetime scope?</p>
  
  <p>According to Autofac documentation, </p>
  
  <blockquote>
    <p>If you register an object as InstancePerDependency() and call the
    delegate factory multiple times, you’ll get a new instance each time.</p>
  </blockquote>
  
  <p><em>This is not true when injecting the factory into the constructor of a class within an existing lifetime scope</em></p>
  
  <p>Some additional background: I'm attempting to use <a href="http://Autofac%20Delegate%20Factories" rel="nofollow noreferrer">Autofac Delegate Factories</a> in order to create a <em>new instance</em> of a ValueObject class each time.</p>
  
  <p>This ValueObject class's constructor and delegate factory look like this:</p>
  
  <pre><code>public SlaInMinutes(int slaInMinutes, ISlaCalculator slaCalculator, ITicketUnitOfWork ticketUnitOfWork)
  public delegate SlaInMinutes Factory(int slaInMinutes);
  </code></pre>
  
  <p>Autofac registration looks like this:</p>
  
  <pre><code>builder.RegisterType&lt;SlaInMinutes&gt;().InstancePerLifetimeScope();
  </code></pre>
  
  <p>When I inject the Factory delegate into a class constructor (<code>SlaInMinutes.Factory slaFactory</code>) within an existing LifetimeScope  I am able to instantiate a new class using the Factory parameter, and Autofac takes care of the remaining constructor dependencies. It's great.</p>
  
  <p>Except it's <em>the same instance every time</em> after I instantiate it once. I need to have <em>an new instance</em> each time I call this Factory delegate based on the Factory parameter int slaInMinutes.</p>
  
  <p>Switching my registration from InstancePerLifetimeScope to InstancePerDependency:</p>
  
  <pre><code> builder.RegisterType&lt;SlaInMinutes&gt;().InstancePerDependency()
  </code></pre>
  
  <p>does not have the effect of creating a new instance each time I call the Factory method.</p>
  
  <p>What I need:</p>
  
  <pre><code>slaFactory.Invoke(1) //new instance
  slaFactory.Invoke(2) //new instance
  slaFactory.Invoke(1) //same instance or new instance, don't care
  </code></pre>
  
  <p>This is an ASP.NET Core 1.0 web app, and the Lifetime scope is started during the beginning of an API endpoint call, and it lasts until that API call is completed.</p>