Reputation: 1
I'm encountering an error in my Blazor WebAssembly application running on .NET 8. The error occurs when the application launches:
InvalidOperationException: Cannot provide a value for property 'Http' on type 'SGC.Client.Layout.NavMenu'. There is no registered service of type 'System.Net.Http.HttpClient'.
This is my Program.cs file on the client-side:
var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.Services.AddHttpClient();
builder.Services.AddScoped(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) });
builder.Services.AddAuthorizationCore();
builder.Services.AddCascadingAuthenticationState();
builder.Services.AddSingleton<AuthenticationStateProvider, PersistentAuthenticationStateProvider>();
builder.Services.AddRadzenComponents();
builder.Services.AddScoped<DialogService>();
builder.Services.AddScoped<NotificationService>();
builder.Services.AddScoped<ContextMenuService>();
builder.Services.AddScoped<TooltipService>();
await builder.Build().RunAsync();
The error occurs when I inject HttpClient into any page. For example:
@page "/example"
@inject HttpClient Http
<h3>Example Page</h3>
How can I resolve this issue and correctly inject HttpClient into my Blazor WebAssembly application?
Ensured HttpClient is registered in the services in Program.cs.
Upvotes: 0
Views: 745
Reputation: 5476
You want to use IHttpClientFactory when creating HttpClients, because there's some underlying code that manages the lifetime of sockets etc. You can read more of it here to decide the best way of implementing your required DI pattern:
Upvotes: 0