I want to make Http calls from a service in Blazor rather than making calls in the @code
block in the .razor
file nor in a code-behind. I receive the error:Shared/WeatherService.cs(16,17): error CS0246: The type or namespace name 'HttpClient' could not be found (are you missing a using directive or an assembly reference?)
The documentation shows that this is how it's done.
Complex services might require additional services. In the prior example, DataAccess might require the HttpClient default service. @inject (or the InjectAttribute) isn't available for use in services. Constructor injection must be used instead. Required services are added by adding parameters to the service's constructor. When DI creates the service, it recognizes the services it requires in the constructor and provides them accordingly.
How do I remedy the error?
// WeatherService.cs
using System.Threading.Tasks;
namespace MyBlazorApp.Shared
{
public interface IWeatherService
{
Task<Weather> Get(decimal latitude, decimal longitude);
}
public class WeatherService : IWeatherService
{
public WeatherService(HttpClient httpClient)
{
...
}
public async Task<Weather> Get(decimal latitude, decimal longitude)
{
// Do stuff
}
}
}
// Starup.cs
using Microsoft.AspNetCore.Components.Builder;
using Microsoft.Extensions.DependencyInjection;
using MyBlazorApp.Shared;
namespace MyBlazorApp
{
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<IWeatherService, WeatherService>();
}
public void Configure(IComponentsApplicationBuilder app)
{
app.AddComponent<App>("app");
}
}
}
using System.Net.Http;
to have access to the class inWeatherService.cs
– Nkosi