HttpClientFactory HttpClient Cannot access a disposed object

Viewed 80

I am implementing a service for posting data to an external RestAPI.

What I did as below:

  1. Service definition:

    public class ExternalOutputService : IExternalOutputService
    {
        private readonly HttpClient _httpClient;
    
        public ExternalOutputService(HttpClient httpClient)
        {
            _httpClient = httpClient;
        }
    
        public async Task<object> Send(object data, string baseAddress, string uri)
        {
            try
            {
                HttpResponseMessage response = await _httpClient.PostAsJsonAsync(uri, data);
                response.EnsureSuccessStatusCode();
    
            }
            catch (Exception ex) {
                Console.Write(ex.Message);
            }
    
            return response.Content;
        }  
    }
    
    
  2. Add services.AddHttpClient<IExternalOutputService, ExternalOutputService>(); in Startup

  3. Use the injected the service and call the Send method.

public class ConfigurableOutput
{
    private readonly IExternalOutputService _externalOutputService;
    public ConfigurableOutput(IExternalOutputService externalOutputService) 
    {
        _externalOutputService = externalOutputService;
    }
    public override async Task<object> Run(object input)
    {
       await _externalOutputService.Send(input.data, "URI address");
    }
 }

But when I run it and hit the httpclient send line, it would throw an exception with 'Cannot access a disposed object'

Anyone has idea or advice?

Hi guys, I finally find the issue.

In another DI extension class, the class has already been registered.

context.Services.AddTransient<IExternalOutputService, ExternalOutputService>();

So removed this line and only keeps

 services.AddHttpClient<IExternalOutputService, ExternalOutputService>();

It is all good now.

0 Answers
Related