Is there any issue with below implementation inside Blazor component? A lot of examples repeatedly use CreateClient
inside every method and I am wondering if it can be handled by a property, in one place to avoid repetition.
@inject IHttpClientFactory ClientFactory
@code{
private HttpClient Client => ClientFactory.CreateClient("api");
private object myData;
private async Task GetData()
{
myData = await Client.GetFromJsonAsync<MyClass>("endpoint");
}
}
Your code is fine.
The HttpClientFactory
will take care of disposal of HttpMessageHandler
s.
The =>
syntax essentially means that you've created an Alias (left-hand side) for running code (right-hand side).
In other words, you ARE calling CreateClient inside every method, except you've made your life a little easier by using an Alias Client
.