I am currently learning Blazor web assembly. I have created a Blazor web assembly sandbox on .NET 6. I want to create an object that can't be reloaded on the entire lifecycle of the app, in order to share it between pages. So, I want to create it as a singleton. But I get this error:

Here is the code of Program.cs:
using BlazorAppWebAsmSandbox.Client;
using Microsoft.AspNetCore.Components.WebAssembly.Hosting;
var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.Services.AddSingleton<GuidObject>();
await builder.Build().RunAsync();
GuidObject:
namespace BlazorAppWebAsmSandbox.Client
{
public class GuidObject
{
public Guid id { get; set; } = Guid.NewGuid();
}
}
And here is how I use it:
@page "/counter"
@rendermode InteractiveWebAssembly
@inject GuidObject guidObject
<PageTitle>Counter</PageTitle>
<h1>Counter</h1>
<p role="status">Current count: @currentCount</p>
<p role="status">guidObject @guidObject.id</p>
<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>
@code {
private int currentCount = 0;
private void IncrementCount()
{
currentCount++;
}
}
Thanks for your help
You will need to register it in the project that implements the interactive web assembly too.
This is because the page is pre-rendered on the server, and later it is also rendered on the client using WebAssembly. Thus the type must be registered both in the web server project and in the WebAssembly project.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With