-
Notifications
You must be signed in to change notification settings - Fork 10.5k
Closed
Labels
DoneThis issue has been fixedThis issue has been fixedarea-blazorIncludes: Blazor, Razor ComponentsIncludes: Blazor, Razor ComponentsbugThis issue describes a behavior which is not expected - a bug.This issue describes a behavior which is not expected - a bug.feature-blazor-wasmThis issue is related to and / or impacts Blazor WebAssemblyThis issue is related to and / or impacts Blazor WebAssembly
Milestone
Description
Describe the bug
Consider the following scenario in a blazor client-side app:
public class ScopedService
{
public ScopedService()
{
Console.WriteLine("Scoped Service created");
}
}
public class AppState
{
private readonly ScopedService scopedService;
public AppState(ScopedService scopedService)
{
this.scopedService = scopedService;
}
}
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<AppState>();
services.AddScoped<ScopedService>();
}
//...
}MyComponent.cshtml
@inject AppState state
<h1>Component that injects AppState and contains ComponentThatUsesScopedService</h1>
<ComponentThatUsesScopedService />ComponentThatUsesScopedService.cshtml
@inject ScopedService service
<h1>ComponentWithScopedService</h1>Expected behavior
According to documentation
Client-side Blazor doesn't currently have the concept of DI scopes. Scoped behaves like
Singleton. However, ASP.NET Core Razor Components support the Scoped lifetime. In a Razor
Component, a scoped service registration is scoped to the connection. For this reason, using
scoped services is preferred for services that should be scoped to the current user, even if
the current intent is to run client-side in the browser.
The ScopedService class should behave like a singleton and be created only once.
Actual behavior
The ScopedService class is created more than once:
WASM: Scoped Service created
WASM: Scoped Service created
Is this behaviour intended ? If so then this is a problem for library authors that want to support both Blazor client-side and server-side and need to register services "per-connection" in the DI.
If the consumer of your library in a blazor client-side app uses singleton registration and depends on your scoped service, then this may lead to wierd bugs.
Metadata
Metadata
Assignees
Labels
DoneThis issue has been fixedThis issue has been fixedarea-blazorIncludes: Blazor, Razor ComponentsIncludes: Blazor, Razor ComponentsbugThis issue describes a behavior which is not expected - a bug.This issue describes a behavior which is not expected - a bug.feature-blazor-wasmThis issue is related to and / or impacts Blazor WebAssemblyThis issue is related to and / or impacts Blazor WebAssembly