I have a class that wraps a DI'ed HttpClient and has some standard function that employ the use of Polly. I would inherit classes from this HttpClientEx class and utilize its common functionality in my other code.
Recently a requirement came up that our messages to/from httpclient should be logged. I added an HttpMessageHandler that implemented some common logging functionality but now I have a problem:
When I invoke any of my Gets/Posts etc. using Polly:
await polPolly.ExecuteAsync(async(ctCancelToken)=>
{
return await HttpClient.GetAsync(sUrl, ctCancelToken);
}, CancellationToken.None);
It throws the exception: Cannot access a disposed object. Object name: 'System.Net.Http.HttpConnection+HttpConnectionResponseContent'
I've read online that this could be because I'm not making my message handler "re-usable" and that Polly is causing this to be disposed causing this problem. All the examples I see out there for HttpMessageHandlers that address this show new HttpClient(SomeMessageHandler, false) as the "fix"... BUT: This isn't a fix. You aren't even supposed to use HttpClient in this fashion. It is supposed to be DI'ed...
So the question is: How do I specify my handler is reusable in a way that complies with the proper way to use HttpClient
? I'm open to using IHttpClientFactory
or Typed HttpClients...
Either will do. I can't seem to find a way to configure this property.
Thanks!
James