Async calls inside constructor

ANB 181 Reputation points
2022-09-26T17:48:50.923+00:00

I have a service and inside its constructor, I make 2 asynchronous calls.
However I am getting the message "the await operator can only be used within an async method. Consider marking this method with the async modifier and changing its return type to Task"

public MyService(HttpClient httpClient) {
_httpClient = httpClient;
_httpClient.DefaultRequestHeaders.Add("param1", await _localStorageService.GetItemAsync<string>("param1");
_httpClient.DefaultRequestHeaders.Add("param2", await _localStorageService.GetItemAsync<string>("param2");
}

This methods come from a nuget package Blazored.Localstorage.
So how can I make this work ?

Thanks

Developer technologies ASP.NET ASP.NET Core
{count} votes

1 answer

Sort by: Most helpful
  1. Bruce (SqlWork.com) 77,686 Reputation points Volunteer Moderator
    2022-09-26T20:25:10.273+00:00

    constructor method can not be async. you can start an async/task process, but you can not await it.

    as the service calls should all be async. there is an easy fix. provide an async GetHttpclient() routine use instead of using _httpClient directly

    private bool GetHttpClientInit = false;  
    private async Task<HttpClient> GetHttpClient()  
    {  
       if (! GetHttpClientInit)  
       {  
             _httpClient.DefaultRequestHeaders.Add("param1", await _localStorageService.GetItemAsync<string>("param1");  
             _httpClient.DefaultRequestHeaders.Add("param2", await _localStorageService.GetItemAsync<string>("param2");  
             GetHttpClientInit = true;  
       }  
       return _httpClient;  
    }  
    
    
    
     
    

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.