Application State and Understanding DI

Learn the basics of the application state and how to preserve it using DI in Blazor WebAssembly.

Application state

In a Blazor WebAssembly app, the browser's memory is used to hold the application's state. This means that when the user navigates between pages, the state is lost, unless we preserve it. We will be using the AppState pattern to preserve the application's state.

In the AppState pattern, a service is added to a DI container to coordinate the state between related components. The service contains all of the states that need to be maintained. Because the service is managed by the DI container, it can outlive individual components and retain the state of the application as the UI is changing.

The service can be a simple class or a complex class. One service can be used to manage the state of multiple components across the entire application. A benefit of the AppState pattern is that it leads to a greater separation between presentation and business logic.

Note: The application state that is held in the browser's memory is lost when the user reloads the page.

For the project in this chapter, we will use a DI service instance to preserve the application's state.

Understanding DI

DI is a technique in which an object accesses services that have been configured in a central location. The central location is the DI container. When using DI, each consuming class does not need to create its own instance of the injected class that it has a dependency on. It is provided by the framework and is called a service. In a Blazor WebAssembly application, the services are defined in the Program.Main method of the program.cs file.

We have already used DI in this course with the following services:

  • HttpClient

  • IJSRuntime

  • NavigationManager

DI container

When a Blazor WebAssembly application starts, it configures a DI container. The DI container is responsible for building the instances of the service and lives until the user closes the tab in their browser that is running the web app. In the following example, the CartService implementation is registered for IcartService:

Get hands-on with 1200+ tech skills courses.