You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: docs/core/extensions/scoped-service.md
+14-19Lines changed: 14 additions & 19 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -3,13 +3,13 @@ title: Use scoped services within a BackgroundService
3
3
description: Learn how to use scoped services within a BackgroundService in .NET.
4
4
author: IEvangelist
5
5
ms.author: dapine
6
-
ms.date: 12/13/2023
6
+
ms.date: 11/06/2024
7
7
ms.topic: tutorial
8
8
---
9
9
10
10
# Use scoped services within a `BackgroundService`
11
11
12
-
When you register implementations of <xref:Microsoft.Extensions.Hosting.IHostedService> using any of the <xref:Microsoft.Extensions.DependencyInjection.ServiceCollectionHostedServiceExtensions.AddHostedService%2A> extension methods - the service is registered as a singleton. There may be scenarios where you'd like to rely on a scoped service. For more information, see [Dependency injection in .NET: Service lifetimes](dependency-injection.md#service-lifetimes).
12
+
When you register implementations of <xref:Microsoft.Extensions.Hosting.IHostedService> using any of the <xref:Microsoft.Extensions.DependencyInjection.ServiceCollectionHostedServiceExtensions.AddHostedService%2A> extension methods—the service is registered as a singleton. There might be scenarios where you'd like to rely on a scoped service. For more information, see [Dependency injection in .NET: Service lifetimes](dependency-injection.md#service-lifetimes).
13
13
14
14
In this tutorial, you learn how to:
15
15
@@ -32,60 +32,55 @@ In this tutorial, you learn how to:
32
32
33
33
## Create scoped services
34
34
35
-
To use [scoped services](dependency-injection.md#scoped) within a `BackgroundService`, create a scope. No scope is created for a hosted service by default. The scoped background service contains the background task's logic.
35
+
To use [scoped services](dependency-injection.md#scoped) within a `BackgroundService`, create a scope with the <xref:Microsoft.Extensions.DependencyInjection.IServiceScopeFactory.CreateScope?displayProperty=nameWithType> API. No scope is created for a hosted service by default. The scoped background service contains the background task's logic.
The preceding interface defines a single `DoWorkAsync` method. To define the default implementation:
40
-
41
-
- The service is asynchronous. The `DoWorkAsync` method returns a `Task`. For demonstration purposes, a delay of ten seconds is awaited in the `DoWorkAsync` method.
42
-
- An <xref:Microsoft.Extensions.Logging.ILogger> is injected into the service.:
39
+
The preceding interface defines a single `DoWorkAsync` method. Create an implementation in a new class named *DefaultScopedProcessingService.cs*:
The hosted service creates a scope to resolve the scoped background service to call its `DoWorkAsync` method. `DoWorkAsync` returns a `Task`, which is awaited in `ExecuteAsync`:
43
+
- An <xref:Microsoft.Extensions.Logging.ILogger> is injected into the service using a primary constructor.
44
+
- The `DoWorkAsync` method returns a `Task` and accepts the <xref:System.Threading.CancellationToken>.
45
+
- The method logs the instance identifier—the `_instanceId` is assigned whenever the class is instantiated.
47
46
48
47
## Rewrite the Worker class
49
48
50
49
Replace the existing `Worker` class with the following C# code, and rename the file to *ScopedBackgroundService.cs*:
In the preceding code, an explicit scope is created and the `IScopedProcessingService` implementation is resolved from the dependency injection service scope factory. The resolved service instance is scoped, and its `DoWorkAsync` method is awaited.
53
+
In the preceding code, while the `stoppingToken` isn't canceled, the `IServiceScopeFactory`is used to create a scope. From the `IServiceScope`, the `IScopedProcessingService`is resolved. The `DoWorkAsync` method is awaited, and the `stoppingToken` is passed to the method. Finally, the execution is delayed for 10 seconds and the loop continues. Each time the `DoWorkAsync` method is called, a new instance of the `DefaultScopedProcessingService` is created and the instance identifier is logged.
55
54
56
55
Replace the template *Program.cs* file contents with the following C# code:
The services are registered in (*Program.cs*). The hosted service is registered with the `AddHostedService` extension method.
59
+
The services are registered in (*Program.cs*). The hosted service is registered with the <xref:Microsoft.Extensions.DependencyInjection.ServiceCollectionHostedServiceExtensions.AddHostedService*> extension method.
61
60
62
61
For more information on registering services, see [Dependency injection in .NET](dependency-injection.md).
63
62
64
63
## Verify service functionality
65
64
66
65
[!INCLUDE [run-app](includes/run-app.md)]
67
66
68
-
Let the application run for a bit to generate several execution count increments. You will see output similar to the following:
67
+
Let the application run for a bit to generate several calls to `DoWorkAsync`, thus logging new instance identifiers. You see output similar to the following logs:
0 commit comments