title: .net core dependency injection to hosted service
body: <p>My .net core app needs to crawl data in a specified time interval. I have chosen to implement <code>IHostedService</code> to run it in parallel with API. The hosted service needs some services injected. I register them in <code>startup.cs</code>, but I get an error:</p>
  <blockquote>
  <p>System.InvalidOperationException: 'Cannot consume scoped service 'IXService' from singleton 'Microsoft.AspNetCore.Hosting.Internal.HostedServiceExecutor'.'</p>
  </blockquote>
  <p><strong>My startup.cs:</strong></p>
  <pre><code>services.AddScoped&lt;IXService, XService&gt;();
  services.AddHostedService&lt;MyHostedService&gt;();
  </code></pre>
  <p>I had a similar problem yet with DbContext, I solved it with <a href="https://stackoverflow.com/a/48368934/8475133">https://stackoverflow.com/a/48368934/8475133</a>, but this time I need dependency injection going through deeper layers and dealing with IServiceScopeFactory in each doesn't seem to be an elegant solution.</p>