PlayFab/consuldotnet

Unable to provide custom HttpClient and/or HttpMessageHandler

Opened this issue · 3 comments

Hello.
I've notice that current ConsulClient constructors don't allow us to provide a custom HttpClient/HttpMessageHandler instances. We can only override configuration of default instances created inside the library through Action<HttpClient>/Action<HttpClientHandler>. This prevents from adding any HttpMessageHandler to inner HttpClient. Why would I want to do that? For example for tracing/diagnostics/logging of HTTP class made by ConsulClient.

Let me guess, HttpClient has to have the message handler passed at construction time, doesn't it? There have been so many edge cases around this with people wanting custom clients, and most of the problem is that I can't then cleanly handle disposing of the client when the ConsulClient goes away nor can I assume that the defaults I need to talk to Consul (e.g. accept encodings etc.) are there.

You could probably do something hacky like:

var client = new ConsulClient(null, hc => { hc = new System.Net.Http.HttpClient(myHandler); });

It should work but it would totally break stuff like tokens in headers and such because that's how we pass them around - there's a HttpClientHandler that provides the headers.

If you have any suggestions on how to handle this cleanly other than just allowing the user to pass a custom client and praying it's configured well, let me know.

Yeah, once you create a HttpClient instance you cannot change its HttpMessageHandler, and that's actuallny not a bad design.

Your hacky solution won't work. This code will overwrite only local hc variable and it won't have any effect. You would have to change Action<HttpClient> into Func<HttpClient> or Func<HttpClient, HttpClient> or simply made it a configureable property.


Maybe you could use HttpClientFactory? That way you could create your own "final"/"deepest" handler, manage control over its configuration and at the same time let me extend HttpClients behaviour through a set of external DelegatingHandlers..

About disposing, maybe just follow HttpClient/HttpClientFactory policy and introduce additional contructor parameter disposeHandler and let me decide whether or not ConsulClient should dispose my custom handler or even entire HttpClient while disposing itself?

Any chance to resolve somehow this issue? ;-)