.Net MAUI Android: Cannot access a disposed object 'System.Net.Http.HttpClient', when calling an API again, for first time it works fine. . My Old code:
public class NetworkClient { private static readonly Lazy<HttpClient> _clientInstance = new Lazy<HttpClient>(() => { HttpClient client = new HttpClient(); client.BaseAddress = new Uri(Constants.BASE_URL); string jwtToken = new SessionManager().getToken(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", jwtToken); return client; }); private NetworkClient() { } public static HttpClient GetClient() { return _clientInstance.Value; } }
Working Solution (Creating new Instance every time, As it's not a best practice but had no other solution for now.):
public class NetworkClient { /* Method to get the HttpClient instance , Everytime new to avoid: System.ObjectDisposedException: 'Cannot access a disposed object */ public static HttpClient GetClient() { HttpClientHandler handler = new HttpClientHandler(); HttpClient client = new HttpClient(handler, false); client.BaseAddress = new Uri(Constants.BASE_URL); string jwtToken = new SessionManager().getToken(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", jwtToken); return client; } }