title: Injecting IServiceProvider into Factory Class with Autofac
body: <p>I have a factory class in a Net Core 3 console app which needs to be able to resolve against a DI container at runtime:</p>
  
  <pre><code>public class OptionFactory : IOptionFactory
  {
      private readonly IServiceProvider _svcProvider;
  
      public OptionFactory( IServiceProvider svcProvider )
      {
          _svcProvider = svcProvider;
      }
  
      public IOption&lt;T&gt;? CreateOption&lt;T&gt;( params string[] keys )
      {
          // code eliminated for brevity
          try
          {
              return retVal = _svcProvider.GetRequiredService&lt;Option&lt;T&gt;&gt;();
          }
          catch( Exception e )
          {
              return null;
          }
      }
  }
  </code></pre>
  
  <p>I'm using Autofac to define the DI container and then "assign" it to <code>IServiceProvider</code> via <code>new AutofacServiceProvider( builder.Build() )</code> in a provider class:</p>
  
  <pre><code>public class TestServiceProvider 
  {
      public static IServiceProvider Instance { get; private set; }
  
      static TestServiceProvider()
      {
          var builder = new ContainerBuilder();
  
          builder.RegisterType&lt;OptionFactory&gt;()
              .As&lt;IOptionFactory&gt;()
              .SingleInstance();
  
          // code omitted for brevity
          Instance = new AutofacServiceProvider( builder.Build() );
      }
  }
  </code></pre>
  
  <p>I'm unclear about how to register <code>IServiceProvider</code> itself with the DI container so that it can be injected into the constructor. Is that even possible? It seems a little self-referential, which could be problematic.</p>
  
  <p>All the examples I've seen online call for referencing back to the Autofac <code>IContainer</code> itself, (or to <code>TestServiceProvider.Instance</code> in my example). I can do that, but it would end tie my library to a concrete service provider class. Which I think I'd like to avoid if I can.</p>
  
  <p>I realize injecting <code>IServiceProvider</code> is considered an anti-pattern by some/many, although others deem it acceptable in a factory class because the factory is "simply" extending the DI container. I'm open to other approaches which don't rely on a factory class, provided they allow me to create concrete instances of open generic types at runtime.</p>