1

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?

Nkosi
  • 235,767
  • 35
  • 427
  • 472
Rocklan
  • 7,888
  • 3
  • 34
  • 49
  • Assuming you understand difference between 3 "lifetimes" (scoped, transient, singleton) it should not be a problem to decide which one to pick... Clearly in you case with a single resolution over the program's lifetime it absolutely does not matter which one to pick... – Alexei Levenkov Jul 27 '21 at 02:22
  • `AddScoped()` is mainly used in the context of HTTP Requests in asp.net. During the lifetime of a request, only one instance of the scoped class will be created. – Ripal Barot Jul 27 '21 at 03:34
  • 2
    "AddScoped() scopes the ScopedProcessingService to the lifetime of the Http Request" Well yes, but actually no. The kestrel web server creates a scope per request. But you can create scopes for any other reason. You'd create a scoped service like the example, so that your scoped service will be disposed when the `using var scope = ` variables is disposed. – Jeremy Lakeman Jul 27 '21 at 03:34
  • 1
    Check these answers [Answer1](https://stackoverflow.com/questions/52020799/net-core-dependency-injection-to-hosted-service) [Answer2](https://stackoverflow.com/questions/48368634/how-should-i-inject-a-dbcontext-instance-into-an-ihostedservice/48368934#48368934) – Matt Qafouri Jul 27 '21 at 07:07

0 Answers0