Search code examples
c#dependency-injectionblazorblazor-webassemblywebassembly

Blazor WebAssembly returns "no registered service" even though service is registered


I have a Blazor app with WebAssembly render mode. In my Client project, I have this page:

@page "/demo"
@page "/{lang}/demo"
@inject IDemoService DemoService
@inject ICsvImportService CsvImportService
@inject ILanguageService LanguageService
...
@code {
    [Parameter]
    public required string Lang { get; set; }

    protected override void OnParametersSet()
    {
        text =  LanguageService.GetLocalizedStrings("AppName.Client.Localization.Strings.Demo.csv", Lang ?? Constants.SupportedLanguages[0]);
    }
...
}

The services are registered in Client's Program.cs like this:

string apiUrl = "https://localhost:7254"; // TODO move to appsettings.json
string apiVersion = "/api/v1";

builder.Services.AddRefitClient<IDemoService>()
    .ConfigureHttpClient(c => c.BaseAddress = new Uri($"{apiUrl}{apiVersion}"));

builder.Services.AddScoped<IEmbeddedCsvService, EmbeddedCsvService>();
builder.Services.AddScoped<ILanguageService, LanguageService>();
builder.Services.AddScoped<ICsvImportService, CsvImportService>();

Usually, everything works fine. But sometimes, for example when I manually change the language code in the URL, the browser shows me this error:

InvalidOperationException: Cannot provide a value for property 'DemoService' on type 'AppName.Client.Features.Calculation.Demo.Page.Demo'. There is no registered service of type 'AppName.Client.Features.Calculation.Demo.Service.IDemoService'.

Suddenly, the service is not registered, but when the page is loaded and I use it to call the API, everything works. Should I change the way I deal with language versions?

EDIT: It happens even with other services unrelated to Refit and even if I keep the language version unchanged.


Solution

  • During Static Server rendering,it requires services from the service container in server side

    As stated in the document,the two following approaches would both resolve this problem:

    Register the service in the main project to make it available during component prerendering.

    If prerendering isn't required for the component, disable prerendering by following the guidance in ASP.NET Core Blazor render modes. If you adopt this approach, you don't need to register the service in the main project.