My .net core app needs to crawl data in a specified time interval. I have chosen to implement IHostedService
to run it in parallel with API. The hosted service needs some services injected. I register them in startup.cs
, but I get an error:
System.InvalidOperationException: 'Cannot consume scoped service 'IXService' from singleton 'Microsoft.AspNetCore.Hosting.Internal.HostedServiceExecutor'.'
My startup.cs:
services.AddScoped<IXService, XService>();
services.AddHostedService<MyHostedService>();
I had a similar problem yet with DbContext, I solved it with https://mcmap.net/q/144128/-how-to-consume-a-scoped-service-from-a-singleton, 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.
DbContext
why couldn't you resolve it for the rest of the servicesMyHostedService
needs? – Katheleenkatherin