local-storageblazor-client-sideblazored

Blazored.LocalStorage in client service


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;
        }

Solution

  • 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.