Singleton Service

Scoped service is a service type in Blazor Server DI. Singleton services are better for:

  1. Logging.
  2. Caching.
  3. Logics that are not based on users.
  4. State is required and have the same state for entire website.
Download the example for a working example containing the code snippets in this guide.

Creating a single service

  1. Navigate to the Data folder and create the SingletonGuidProviderService.cs class:
using System;

namespace DependencyExampleBlazorSchool.Data
{
    public class SingletonGuidProviderService
    {
        public Guid Id { get; set; } = Guid.NewGuid();
    }
}
  1. Navigate to Startup.cs and register the service as a scoped service.
public void ConfigureServices(IServiceCollection services)
{
    ...
    services.AddSingleton<SingletonGuidProviderService>();
}
For injecting and using a service, please refer to Dependency Injection.

Lifetime

Singleton services are created for the first time the service is requested and exists until the website shutdown. Singleton services are memory efficient because they are created once and reused everywhere. But beware when you use singleton services because any memory leaks will build up over time.

In the example provided at the beginning of this context, you will see a singleton service being injected 2 times and their values are the same every time injected.

Note: Use the "Trigger new request" in the example to create a new request.
BLAZOR SCHOOL
Designed and built with care by our dedicated team, with contributions from a supportive community. We strive to provide the best learning experience for our users.
Docs licensed CC-BY-SA-4.0
Copyright © 2021-2025 Blazor School
An unhandled error has occurred. Reload 🗙