In the guide, you can understand the differences between DI scopes and also how to use them. There are 3 scopes in Blazor WebAssembly:
Despite having 3 scopes, Blazor WebAssembly only has 2 lifetimes.
You can download the example code used in this topic on GitHub.
Singleton/Scoped service is the preferred scope for sharing data between all the components on your website. Singleton/Scoped service lifetimes are within the browser tab, the data in singleton services will be disposed when the user closes its browser tab and will be created when the user opens a new browser tab. Singleton/Scoped services are better for:
Singleton and Scoped services are the same in Blazor WebAssembly. The following image demonstrates the lifetime of a singleton/scoped service.
As you can see in the image, there is only one singleton/scoped service instance for 1 browser tab no matter how many times you inject into a component.
You can register singleton/scope services in Startup.cs
with AddSingleton
/AddScoped
method. The following code sample demonstrates how to register a singleton/scope service.
builder.Services.AddScoped<IGuidProviderScopedService, GuidProviderService>(); builder.Services.AddSingleton<IGuidProviderSingletonService, GuidProviderService>();
You will see the following results:
Singleton/scoped service will always hold a static value no matter how many times you inject it.
However, singleton/scoped service will have different values in multiple browser tabs.
Transient service is the preferred scope for lightweight operations and no state is required. The following image demonstrates the lifetime of a transient service.
Each time you inject a transient service into a component, a new instance of that service will be created then injected to the component. You can register a transient service in Startup.cs
with AddTransient
method. The following code sample demonstrates how to register a transient service.
builder.Services.AddSingleton<IGuidProviderSingletonService, GuidProviderService>();
You will see the following result:
For each injection, transient service will hold a different value.