CodexBloom - Programming Q&A Platform

C# 10 guide with Using HttpClient in Scoped Services - Getting 'ObjectDisposed' handling

👀 Views: 289 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-10
c# asp.net-core httpclient C#

I'm collaborating on a project where I'm relatively new to this, so bear with me... I'm working with a question with `HttpClient` when using it in a scoped service in my ASP.NET Core application. I have set up a service that makes an HTTP call to an external API, and I am injecting `HttpClient` as follows: ```csharp public class MyApiService : IMyApiService { private readonly HttpClient _httpClient; public MyApiService(HttpClient httpClient) { _httpClient = httpClient; } public async Task<string> GetDataAsync(string endpoint) { var response = await _httpClient.GetAsync(endpoint); response.EnsureSuccessStatusCode(); return await response.Content.ReadAsStringAsync(); } } ``` In my `Startup.cs`, I register the `HttpClient` and the service in the `ConfigureServices` method: ```csharp services.AddHttpClient<IMyApiService, MyApiService>(); ``` However, I'm getting an `ObjectDisposed` exception when trying to call the `GetDataAsync` method from a controller, like so: ```csharp public class MyController : ControllerBase { private readonly IMyApiService _myApiService; public MyController(IMyApiService myApiService) { _myApiService = myApiService; } public async Task<IActionResult> FetchData() { var data = await _myApiService.GetDataAsync("https://api.example.com/data"); return Ok(data); } } ``` This happens intermittently, and I'm unsure why `HttpClient` seems to be disposed while executing the request. I've confirmed that the service is being resolved correctly. I suspect it might have something to do with the lifetime of the `HttpClient` being scoped while the request is asynchronous. I've also tried changing to singleton lifetime for the `HttpClient`, but that caused issues with DNS changes in my environment. Any insights on how to properly use `HttpClient` in a scoped service without running into disposal issues would be greatly appreciated! I'm working on a service that needs to handle this. I'd really appreciate any guidance on this. I'm coming from a different tech stack and learning C#. Any ideas what could be causing this?