title: Injecting a factory Func with ASP.NET Core DI
body: <p>I'm trying to get something like this working:</p>
  
  <pre><code>public class FooService : IFooService {
      public FooService(Func&lt;IBarService&gt; barFactory) { ... }
  }
  public class BarService : IBarService, IDisposable { ... }
  
  services.AddSingleton&lt;IFooService, FooService&gt;();
  services.AddTransient&lt;IBarService, BarService&gt;();
  services.AddSingleton&lt;Func&lt;IBarService&gt;&gt;(ctx =&gt; () =&gt; ctx.GetService&lt;IBarService());
  </code></pre>
  
  <p>This works as far as resolving the <code>BarService</code> instance, but I can't figure out how to properly manage its lifetime. When I do this inside one of the members of <code>FooService</code>:</p>
  
  <pre><code>using (var bar = _barFactory())
  {
      ...
  }
  </code></pre>
  
  <p>I get an <code>ObjectDispoedException</code>:</p>
  
  <blockquote>
    <p>System.ObjectDisposedException: Cannot access a disposed object. A common cause of this error is disposing a context that was resolved from dependency injection and then later trying to use the same context instance elsewhere in your application. This may occur if you are calling Dispose() on the context, or wrapping the context in a using statement. If you are using dependency injection, you should let the dependency injection container take care of disposing context instances.</p>
  </blockquote>
  
  <p>However, if I just do <code>var bar = _barFactory();</code>, without the using statement, I have no way to signal to the DI container that I'm done with the instance, and it can be disposed.</p>
  
  <p>What's the correct approach here?</p>
  
  <hr>
  
  <p>(Side note: yes, I know that some will object that a singleton service should not be dependent on a transient service. That's not what's happening here; the singleton service is dependent on a singleton <em>factory</em>, that produces transient instances. The singleton then uses the transient service for one or two statements and then is done with it, so there should be no actual lifetime problems here.)</p>