user16242098
user16242098

Reputation:

Some services are not able to be constructed with blazor server

i have class CustomersService : ICustomersService

with constractor:

public CustomersService(HttpClient http)
{
   this._http = http;
}

and in program.cs file:

builder.Services.AddScoped<ICustomersService, CustomersService>();

How should I reboot/reset the constructor?

builder.Services.AddScoped<ICustomersService, CustomersService>(); the error is:

InvalidOperationException: Unable to resolve service for type 'System.Net.Http.HttpClient'

Upvotes: 0

Views: 503

Answers (1)

MrC aka Shaun Curtis
MrC aka Shaun Curtis

Reputation: 30330

I'm guessing you're in Blazor Server as the HttpClient is registered by default in Web Assembly.

Here's how I do it in Server:

// Server Side Blazor doesn't register HttpClient by default
// Thanks to Robin Sue - Suchiman https://github.com/Suchiman/BlazorDualMode
if (!services.Any(x => x.ServiceType == typeof(HttpClient))
{
     // Setup HttpClient for server side in a client side compatible fashion
     services.AddScoped<HttpClient>(s =>
    {
       // Creating the URI helper needs to wait until the JS Runtime is initialized, so defer it.
       var uriHelper = s.GetRequiredService<NavigationManager>();
       return new HttpClient
       {
          BaseAddress = new Uri(uriHelper.BaseUri)
       };
   });
}

Upvotes: 0

Related Questions