Quantcast
Channel: Active questions tagged blazor - Stack Overflow
Viewing all articles
Browse latest Browse all 4839

Blazor Server, Scoped service seem to be instantiated for each page (or what am I doing wrong?)

$
0
0

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:

  1. Create a Blazor Server project with the test pages

  2. 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");        }    }}
  3. Register the service in Program.cs

    builder.Services.AddScoped<ITestService, TestService>();
  4. 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 intended?


Viewing all articles
Browse latest Browse all 4839

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>