ZCoder
ZCoder

Reputation: 2339

Question Between @inject HttpClient vs @using System.Net.Http; on view page

So what is different between @using System.Net.Http; where you create object and call the method what different between @inject HttpClient Http so i am trying to learn Blazor

Will this work can someone explain me the difference

 @using System.Net.Http;
@code {
    private WeatherForecast[] forecasts;
  
        protected override async Task OnInitializedAsync()
        {
            var Http = new HttpClient();
            forecasts = await Http.GetFromJsonAsync<WeatherForecast[]>("sample-data/weather.json");
        }

or

@page "/fetchdata"
@inject HttpClient Http


    @code {
        private WeatherForecast[] forecasts;
    
        protected override async Task OnInitializedAsync()
        {
            forecasts = await Http.GetFromJsonAsync<WeatherForecast[]>("sample-data/weather.json");
        }

Upvotes: 1

Views: 421

Answers (1)

enet
enet

Reputation: 45596

When you use var Http = new HttpClient();, you create a local variable containing an instance of the HttpClient type.

When you use @inject HttpClient Http, you tell Blazor to create an instance of the HttpClient service and assign it to the property named Http.

The first usage described above is not recommended. You should always inject your objects instead of instantiating them. Injected objects are created by the Dependency Injection system that create your objects, control their life span, and many other benefits you can read about in documents about Dependency Injection.

Upvotes: 4

Related Questions