Scoped service is a service type in Blazor Server DI. Scoped services are better for:
Download the example for a working example containing the code snippets in this guide.
Data
folder and create the ScopedGuidProviderService.cs
class:using System; namespace DependencyExampleBlazorSchool.Data { public class ScopedGuidProviderService : IGuidProviderService { public Guid Id { get; set; } = Guid.NewGuid(); } }
Startup.cs
and register the service as a scoped service.public void ConfigureServices(IServiceCollection services) { ... services.AddScoped<ScopedGuidProviderService>(); }
For injecting and using a service, please refer to Dependency Injection.
Scoped services are created for each user request. Used for maintaining state within a request.
In the example provided at the beginning of this context, you will see a scoped service being injected 2 times and their values are different for each request.
Note: Use the "Trigger new request" in the example to create a new request.