2
votes

How can you inject Blazored.LocalStorage (v2.1.6) into a blazor webassembly service (3.2.0)?

Here is what we tried. Getting null error when trying to await LocalStorage.GetItemAsync.

App.razor

@using Blazored.LocalStorage

Program.cs

builder.Services.AddBlazoredLocalStorage();
builder.Services.AddSingleton<Services.UserService>();

Services/UserService.cs

namespace Test.Client.Services
{
    public class UserService
    {
        [Inject]
        private ILocalStorageService LocalStorage;
        private readonly HttpClient Http;

        public UserService(HttpClient _http)
        {
            Http = _http;
        }

        public async void LoginCallback()
        {
            string tkn = await LocalStorage.GetItemAsync<string>("tkn"); //Object null error here
        }
    }
}

Edit Solution: First, restart Visual Studio because it was holding onto something and would not work for anything until I did. Then as the marked answer shows, DI like so:

        private ILocalStorageService LocalStorage;
        private readonly HttpClient Http;

        public UserService(HttpClient _http, ILocalStorageService _localStorage)
        {
            Http = _http;
            LocalStorage = _localStorage;
        }
2

2 Answers

0
votes

You must first inject using @inject <IService> <serviceInstanceName>

Example:

@using Blazored.SessionStorage
@inject ISessionStorageService sessionStorageService
...
@code
{
     var eml = sessionStorage.sessionStorageService.GetItemAsync<string>("emailAddress");
}

EDIT: Sorry I misinterpreted. The above is to inject session storage to a razor page. If you wanted to inject into a class you do below:

public class SomeClass
{
    private ISessionStorageService _sessionStorageService;
        

    // inject in the class constructor
    public SomeClass(ISessionStorageService sessionStorageService)
    {
        _sessionStorageService = sessionStorageService;
    }
}

This is on top of registering the service in your Program.cs (in Client) which you have done already.

0
votes

I encountered the same issue and tried restarting my Visual Studio, as well as my computer, both didn't help, but then found this somewhat related post: https://github.com/dotnet/aspnetcore/issues/10143

Apparently, we need to check for null if the data is being fetched in the OnInitializedAsync function, just like in the FetchData.razor example:

@if (forecasts == null)
{
    <p><em>Loading...</em></p>
}
else
{