I've created a .NET8 Blazor project (a client and server side) and added the Blazored.LocalStorage nuget package for the client side. In the Program.cs
file I'm adding the service registration line:
builder.Services.AddBlazoredLocalStorage();
Then, on a page where I want to use it I inject the instance with:
@inject ILocalStorageService _localStorage
Unfortunately, when I start the webapp, I see the error in the browser:
InvalidOperationException: Cannot provide a value for property '_localStorage' on type 'MyProject.Client.Pages.Login'. There is no registered service of type 'Blazored.LocalStorage.ILocalStorageService'.
What am I doing wrong?
To check if you are using global rendermode or not, you could open the "server project" -Components- App.razor.
Global:
<HeadOutlet @rendermode="InteractiveWebAssembly" />
<Routes @rendermode="InteractiveWebAssembly" />
Per page: you need to manually add @rendermode InteractiveWebAssembly
at any top of each page. (When you don't add, it only use server-side-rendering)
<HeadOutlet />
<Routes />
There is no registered service of type 'Blazored.LocalStorage.ILocalStorageService'.
You need to add builder.Services.AddBlazoredLocalStorage();
to both server project and client project. This is because @rendermode InteractiveWebAssembly
will still prerender on server 1st. The prerender SSR(server-side rendering) is executed in the server project .
But as SSR actually cannot access localstorage at all. You will need to disable prerender. To do this:
If you are using global rendermode, change the App.razor like
<Routes @rendermode="new InteractiveWebAssemblyRenderMode(false)" />
If you are using per component, add rendermode at top of page like
@rendermode @(new InteractiveWebAssemblyRenderMode(false))