0

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");
    }
}
3
  • "Is there any issue with below implementation inside Blazor component?" From a design standpoint, you're piling all your data access into your component. Your component has lots of responsibilities. It's getting the data, managing the data and displaying the data: there's no "Separation of Concerns." If you're Ok with that, continue. Commented Jan 11, 2023 at 18:06
  • @MrCakaShaunCurtis how instead should I write component that displays data from the api? Commented Jan 11, 2023 at 19:06
  • 1
    @Pawel - ideally move the code to access the API into a typed HttpClient (see learn.microsoft.com/en-us/dotnet/architecture/microservices/… ... Then that typed client can hide the API access and deserialization into required types, e.g. MyClass. Commented Jan 11, 2023 at 20:11

1 Answer 1

1

Your code is fine.

The HttpClientFactory will take care of disposal of HttpMessageHandlers.

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.