'Why Scoped service in Blazor server App will not create new instance to each device?
I use core 6 and initiate a class named DAL as a scoped service in blazor server app.
Instead of creating new DAL instance to each connected device it uses the same instance to all of the devices.
I tested it in debug mode and it actually hit the services.AddScoped<DAL>(); line only once.
Any ideas ? Thanks
Startup.cs
[Obsolete]
public void ConfigureServices(IServiceCollection services)
{
//This command is for API route
services.AddMvc(setupAction: Options => Options.EnableEndpointRouting = false).SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
services.AddRazorPages();
services.AddServerSideBlazor();
services.AddSingleton<WeatherForecastService>();
services.AddSingleton<HttpClient>();
services.AddScoped<DAL>();
services.AddBlazoredSessionStorage();
}
_Host.cshtml
<app>
<component type="typeof(App)" render-mode="Server" />
</app>
Solution 1:[1]
As per @enet's comments - I don't believe this.
The simplest way of testing this is is to assign a GUID to each instance of DAL.
Here's my Blazor Server version.
using System.Diagnostics;
public class DAL
{
public Guid Id { get; } = Guid.NewGuid();
//....
public DAL()
{
Debug.WriteLine($"DAL Service Id created {Id.ToString()}");
}
}
As expected I get a new Id for each browser window opened, which is the same as each device!
Solution 2:[2]
Thanks guys, I found the problem. It was related to my DAL class architecture and how I used it in my razor pages.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | MrC aka Shaun Curtis |
| Solution 2 | Yaron Amar |
