title: How can I use an existing DI container in a new host in ASP.NET Core?
body: <p>I need to create a new host as a background service of a larger ASP.NET core application. This new background service can be created with a reference to the <code>IServiceCollection</code> of the larger host application which I store in a private field of my background service instance.</p>
  <pre class="lang-cs prettyprint-override"><code>public class BackgroundWebHost : BackgroundService
  {
      private readonly IServiceCollection _services;
  
      public BackgroundWebHost (IServiceCollection services)
      {
          _services = services;
      }
  </code></pre>
  <p>I then have this private method to create the host which is then started asynchronously in the <code>ExecuteAsync</code> method of my background service.</p>
  <pre class="lang-cs prettyprint-override"><code>private IHost CreateHost(string[] args)
  {
      return Host.CreateDefaultBuilder(args)
          .ConfigureWebHostDefaults(webBuilder =&gt;
          {
              webBuilder.ConfigureKestrel(options =&gt;
              {
                  options.ListenAnyIP(4999, listenOptions =&gt;
                  {
                      listenOptions.Protocols = HttpProtocols.Http2;
                  });
              });
              webBuilder.UseStartup&lt;Startup&gt;();
          })
          .Build();
  }
  </code></pre>
  <p>The <code>Startup</code> used contains application configuration but additional services can be registered into the larger application's DI container using an exposed API of the larger host application.</p>
  <p>This process works great to get port 4999 open and accepting Http2 connections. However, I want to use dependencies registered in the larger host application, which are registered in the <code>IServiceCollection _services</code> of my background service. I tried looping through them and adding each service into the container created by the background service's host but this takes too long to start up and takes a lot of memory as the larger host application has over 1000 dependencies registered. I figure it must be possible to create a host with a DI container referring to the same one as its parent. Any ideas as to how this could be done?</p>
  <p>Edit: I should clarify that I can not modify the larger host application in any way as my application is a plugin.</p>