dotnet / runtime

.NET is a cross-platform runtime for cloud, mobile, desktop, and IoT apps.
https://docs.microsoft.com/dotnet/core/
MIT License
15.48k stars 4.76k forks source link

Add access to name from HttpClientFactory callbacks #110167

Open CarnaViire opened 1 week ago

CarnaViire commented 1 week ago

Related to #101719

In ConfigureHttpClientDefaults, IHttpClientBuilder.Name will be null by design, because by the time of registration, the name is not known, it will be only known at the moment of execution. In general any "global" (="for all clients") configuration with e.g. ConfigureAll<HttpClientFactoryOptions> -- a specific options (=client's) name is not available. ConfigureHttpClientDefaults aligns to the nature of the Options pattern, which regards null as "all".

However, that means that any callback provided to HttpClientFactory configuration methods, e.g. to AddHttpMessageHandler, can't get the name from the IHttpClientBuilder.Name closure (how it usually does in an "ordinary" named case). And even though by the time the callback is executed, client's name is known already, it is not passed to the callback, and there is no way to access it.

The only existing workaround is to resort to configuration methods/approaches that are not advised to be used, namely the ones giving access to the full HttpMessageHandlerBuilder: ConfigureHttpMessageHandlerBuilder (deprecated), IHttpMessageHandlerBuilderFilter or HttpClientFactoryOptions.HttpMessageHandlerBuilderActions.

We should introduce a new API to enable access to the specific client name from within the callbacks registered via ConfigureHttpClientDefaults

dotnet-policy-service[bot] commented 1 week ago

Tagging subscribers to this area: @dotnet/ncl See info in area-owners.md if you want to be subscribed.

julealgon commented 1 week ago

This to me feels like the whole concept of named options should be redesigned and be built around keyed registrations.

Named options were introduced at a point where there was no support for named or keyed registrations in the container and basically ended up being a gigantic hack around the lack of that capability.