In my .NET 8 Blazor solution, I created a project for the application's services, such as API calls.
In the Program.cs
in the server project, I added the dependency like this:
builder.Services.AddScoped<ClientService>();
Then, in the client project, on the page, I use the Inject
to get an instance of the service like
@rendermode InteractiveAuto
@code {
[Inject] public ClientService? _clientService { get; set; }
}
The first time the page is loaded, it works fine. However, if I refresh the page, for example, with Ctrl+F5, the _clientService
is null.
How can I avoid this error?
When using @rendermode InteractiveAuto
, Blazor dynamically switches between Server and WebAssembly rendering modes based on the client's capabilities.
If the service (ClientService)
is registered only on the server side, it won't be available in the WebAssembly context when the page refreshes.
because When you refresh the page (e.g., Ctrl+F5), the WebAssembly runtime is reinitialized, and the dependency injection container in the WebAssembly context may not have the service registered.
To resolve this issue, you need to ensure that ClientService
is registered in both the server and client projects.
// Register ClientService
builder.Services.AddScoped<ClientService>();