I am implementing a service for posting data to an external RestAPI.
What I did as below:
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; } }Add
services.AddHttpClient<IExternalOutputService, ExternalOutputService>();in StartupUse 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.