Why Scoped service in Blazor server App will not create new instance to each device?

236 views Asked by At

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>
2

There are 2 answers

0
MrC aka Shaun Curtis On

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!

2
Yaron Amar On

Thanks guys, I found the problem. It was related to my DAL class architecture and how I used it in my razor pages.