Reputation: 9360
I can not retrieve the default HttpClient
injected by the server in the Blazor
client.
Configure
public void ConfigureServices(IServiceCollection services)
{
try
{
ServiceProvider prov = services.BuildServiceProvider();
var returned = prov.GetRequiredService<HttpClient>();
if (returned == null) //returns null on Blazor Client
{
Console.WriteLine("is null");
}
else Console.WriteLine(not null httpclient);
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
P.S
Why does this code not work on the Blazor
client and will work without problem on any typical Asp Net Core
application ?
P.S 2 After solving the problem for my given service by first adding it to the service collection and then using GetService< >
i see that this however does not work for HttpClient
.
So the server already injects in the Client.Startup
a HttpClient
; why can't i retrieve it ?
Upvotes: 1
Views: 2017
Reputation: 45626
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<MService>();
}
Note: You should not create a ServiceProvider. It has already been created by code. All you've got to do is add your object to the container. Incidentally, if you do create a ServiceProvider, the ConfigureServices method in which it was created should return it, so other pieces of code can use it.
It is not clear why you want to access the HttpClient service in the ConfigureServices method ! However you can do the following: 1.Inject the IServiceProvider and use it like this:
@inject IServiceProvider services
@functions {
WeatherForecast[] forecasts;
protected override async Task OnInitAsync()
{
var client = services.GetRequiredService<HttpClient>();
forecasts = await client.GetJsonAsync<WeatherForecast[]>("/sample-data/weather.json");
}
}
Build a service provider from the services accessible in the ConfigureServices method:
public void ConfigureServices(IServiceCollection services) {
IServiceProvider Services = services.BuildServiceProvider();
var client = Services.GetRequiredService<HttpClient>();
}
Hope this helps...
Upvotes: 2