There is no registered service of type error in blazor.net when adding a new service

Worth noting that for Blazor WebAssembly, there is no Startup class like the one in Blazor Server. In Blazor WebAssembly we can register Services in Program.cs as below:

public static async Task Main(string[] args)
{
    var builder = WebAssemblyHostBuilder.CreateDefault(args);

    //...other services
    builder.Services.AddSingleton<MyNewService>();

    builder.RootComponents.Add<App>("app");
    await builder.Build().RunAsync();
 }

The newly created service name should be register in the ConfigureServices method in the <applicationName>.App\Startup.cs file.

For example, if the new service name is MyNewService.cs, it should be added as below in the ConfigureServices method.

Sample code:

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        // ... existing services
        services.AddSingleton<MyNewService>();
    }

    ...
    ...

Tags:

Blazor