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