According to the official documentation:
To use scoped services within a BackgroundService, create a scope. No scope is created for a hosted service by default.
That's fine, and it's what the example code does:
using (var scope = Services.CreateScope())
{
var scopedProcessingService =
scope.ServiceProvider
.GetRequiredService<IScopedProcessingService>();
await scopedProcessingService.DoWork(stoppingToken);
}
But then when the IScopedProcessingService
service is registered in IHostBuilder.ConfigureServices
(Program.cs), it is added with AddScoped
:
services.AddScoped<IScopedProcessingService, ScopedProcessingService>();
Is this necessary? According to this, AddScoped()
scopes the ScopedProcessingService
to the lifetime of the Http Request. However, this is a background service, and so there is no Http Request. If I change the code to use AddTransient()
instead, it runs fine:
services.AddTransient<IScopedProcessingService, ScopedProcessingService>();
Is AddScoped()
necessary or just a performance optimisation in case some code that is running inside a Http Request (eg, a Controller) tries to resolve a IScopedProcessingService
service?