loading...
Cover image for Simple state management in Blazor using dependency injection.

Simple state management in Blazor using dependency injection.

askarmus profile image Askar Musthaffa ・2 min read

When we create single-page-applications, there is no way around it. Sooner or later we are going to be facing the state. luckily Blazor gives us many ways to manage the state

in this post, I will go through how to implement a user state using POCO class and dependency injection.

Let's use the default counter component that comes with the default blazer template when you create a new project.

Alt Text

Navigate to counter component page and click the counter button that increases the count and if you go back home page and visit the counter page again the state is gone and count reset to zero because the state has been reset while navigation pages.

Alt Text

So how to preserve the state between page navigation in Blazor? so let's implement to preserve user state using dependency injection.

namespace CunterState.Data
{
    public class CounterState
    {
        public int CurrentCount { get; set; }
    }
}

The purpose of the above POCO class is to add in the project dependency injection service. Open startup.cs file add the inject the CounterState class there.

 public void ConfigureServices(IServiceCollection services)
 {
     services.AddRazorPages();
     services.AddServerSideBlazor();
     services.AddSingleton<WeatherForecastService>();

     services.AddScoped<Data.CounterState>();
 }

I injected using the AddScoped injection method into the container. A very important point is to remember is when choosing the injection method. in Blaozr if you are sharing the state's entire user base AddScoped dependency injection method is a perfect choice for us. if you want to share the sate entire application AddSingleton is the best choice for you.

@page "/counter"
@inject Data.CounterState state
<h1>Counter</h1>

<p>Current count: @state.CurrentCount</p>

<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>

@code {

    private void IncrementCount()
    {
        state.CurrentCount++;
    }
}

CounterState object has been injection using @inject attribute at the top of the page so that state data will be preserved throughout the user interaction.

Now when you run the application and click the counter button, the value will be preserved. Try this by navigating to the home page then navigating back again to the counter page... Awesome!

Thanks for reading and give your feedback int the comment box below.

Discussion

pic
Editor guide