dapr / dotnet-sdk

Dapr SDK for .NET

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Best way to create a Dapr HttpClient with custom delegating handler?

andyfurniss4 opened this issue · comments

I have been wondering how to use DaprClient.CreateInvokeHttpClient when I have my own HTTP delegating handler in use. My custom http handler will get and add an auth token to outgoing requests.

I'd prefer to avoid having Dapr-specific code all over my codebase so I'm trying to use Dapr in conjunction with an IHttpClientFactory. I've created a simple IHttpClientFactory implementation which just calls DaprClient.CreateInvokeHttpClient and I've registered my delegating handler against the named HttpClient service registration. However, after digging into the Dapr code, I can see that it's just hard-coded to use an InvocationHandler and there's no way to change this. So, my custom handler gets lost and never added to the HttpClient created by DaprClient.CreateInvokeHttpClient.

I cam across this issue from a few years ago which proposed resolving this by allowing consumers to pass a custom handler to DaprClient.CreateInvokeHttpClient: #647, but it was rejected with what I think is the suggestion to just manually create your own HttpClient with your own http handler, presumably with the Dapr InvocationHandler as it's internal handler? Is this correct? I could just copy/paste the code from DaprClient.CreateInvokeHttpClient and tweak the http handler bit, but then I have to maintain this and watch for any changes the Dapr team might make in future. This seems somewhat risky. Obviously, as mentioned in the other issue, InvoationHandler is public, so I can create that and set it as the internal handler of my own custom handler, but what about the code within the DaprClient.CreateInvokeHttpClient itself (setting DaprEndpoint, building and setting the user agent, settings base address etc)? This could change at any time and suddenly Dapr could break when upgrading the NuGet version, because maybe there's some new header or something that's expected.

image

Maybe the above scenario is unlikely, but frankly I have no idea what could change in future and even if it's not likely to happen, it still feels pretty ugly.

Any ideas/suggestions?

@andyfurniss4 I'd think I'd be ok with an additional, optional, argument to CreateInvokeHttpClient() that allows passing a delegating handler. That seems like it would be low impact to current users but also prevent you from having to maintain the current implementation.