我看到过很多这样的例子,但这并不适合我。有什么帮助吗?
Program.cs
...
using Blazored.LocalStorage;
using TestFullPage.Classes;
namespace TestFullPage
{
public class Program
{
public static async Task Main(string[] args)
{
var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.RootComponents.Add<App>("#app");
builder.Services.AddScoped(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) });
builder.Services.AddBlazoredLocalStorage();
builder.Services.AddSingleton<Session>();
await builder.Build().RunAsync();
}
}
}
Session.cs
...
using Microsoft.AspNetCore.Components;
using Blazored.LocalStorage;
namespace TestFullPage.Classes
{
public class Session
{
[Inject]
public ILocalStorageService LocalStorage { get; set; }
public void updateLocalStorage()
{
LocalStorage.SetItemAsync("test", "123");
}
}
}
Index.razor
@page "/"
@inject Session sesssion
<button @onclick="() =>Write()">Write to LocalStorage</button>
@code {
public void Write() {
sesssion.updateLocalStorage();
}
}
未处理的异常呈现组件:对象引用未设置为对象的实例。系统。NullReferenceException:对象引用未设置为实例——>LocalStorage.SetItemAsync("test","123");
您正在使用类'Session'作为'组件类',而事实并非如此将它替换为下面的代码,它应该可以工作:
public class Session
{
protected readonly ILocalStorageService _localStorage;
public Session(ILocalStorageService LocalStorage)
{
_localStorage = LocalStorage;
}
public void updateLocalStorage()
{
_localStorage.SetItemAsync("test", "123");
}
}
你需要将'Session'从单例更改为scope,参考这个线程:如何正确使用依赖注入后端在Blazor服务器?