I am pretty new to Blazor, and are building a small Blazor Server application in Visual Studio 2022 and .NET 8.0. I am going to use a Scoped service to keep data within one browser tab session, i.e. “circuit”.
The problem I experience is that my Scoped service keep getting instantiated for each Blazor page separately.
What I have done:
-
Create a Blazor Server project with the test pages
-
Created my service in TestService.cs
namespace BlazorAppScoped.Model
{
public interface ITestService
{
string GetDateTimeStart();
}
public class TestService : ITestService
{
private DateTime _DateTimeStart;
public TestService()
{
_DateTimeStart = DateTime.Now;
}
public string GetDateTimeStart()
{
return _DateTimeStart.ToString("HH:mm:ss");
}
}
}
- Register the service in Program.cs
builder.Services.AddScoped<ITestService, TestService>();
- Injecting the service in the various pages where I need to access it:
@inject ITestService testService
The problem is that when I navigate between the pages, the constructor of the TestService gets called each time. The whole purpose of scoped is to have one instance throughout the App.
If I change step 3 to AddSingleton instead, it works as expected for a Singleton, i.e. there is only one instantiation throughput multiple sessions and multiple tabs.
What am I doing wrong, so that the Scoped does not work as intented?