Dependency injection in Blazor does not work while switching pag

ghz 8months ago ⋅ 87 views

I have a class

public class SessionState 
{
    public int id { get; set; }
    public bool verified { get; set; }
}

And in every page I have injected the class with @inject SessionState state.

I want to fill state.id while the user login, I wrote this code:

state.id = some value;
state.verified = true;
NavigationManager.NavigateTo("home");

And I have this code in Program.cs:

builder.Services.AddScoped<SessionState>();

Now when the web site navigates to Home, I have no value in state.id.

I also used this:

builder.Services.AddSingleton<SessionState>();

but the problem is when user 1 logs in I have state.id = 1, after user1 user2 logs in and I have state.id = 2

How can I have state.id unique for every user that logs in, and I need it in all of my Blazor pages.

state.id = int.Parse(dt.Rows[0]["iduser"].ToString());
state.verified = true;
NavigationManager.NavigateTo("home");

Answers

The issue you're facing stems from the fact that you're registering SessionState as a scoped or singleton service in your Blazor application. Both scoped and singleton services maintain a single instance for the entire application's lifetime, which is why you're experiencing the behavior where state.id is shared among all users or across different sessions.

To achieve the desired behavior where state.id is unique for each user session, you should register SessionState as a transient service. Transient services create a new instance for each request or instantiation, which is suitable for maintaining session-specific data.

Here's how you can update your registration in Program.cs:

builder.Services.AddTransient<SessionState>();

With this change, each time SessionState is injected into a component or service, a new instance will be created, ensuring that state.id is unique for each user session.

Additionally, ensure that you're setting state.id after the user logs in and before navigating to the home page, as you mentioned:

state.id = int.Parse(dt.Rows[0]["iduser"].ToString());
state.verified = true;
NavigationManager.NavigateTo("home");

This will ensure that state.id is properly set before navigating to the home page.