dotnet / dotnet/fsharp

Generic AddHttpClient selected instead of non-generic

Open
#16,422 5 comments 1 reaction 0 assignees View on GitHub
Area-Compiler-Checking Area-Compiler-Checking-Overloads Feature Improvement Needs-More information
Dominant language
F#
Stars
4.3k
Forks
876
Avg merge
4d 22h
Merged PRs (30d)
144

Description

I try to use Named HttpClient as described in the [documentation](https://learn.microsoft.com/en-us/dotnet/api/microsoft.extensions.dependencyinjection.httpclientfactoryservicecollectionextensions.addhttpclient?view=dotnet-plat-ext-8.0#microsoft-extensions-dependencyinjection-httpclientfactoryservicecollectionextensions-addhttpclient(microsoft-extensions-dependencyinjection-iservicecollection-system-string-system-action((system-net-http-httpclient)))) from a Giraffe application.

```
services.AddHttpClient(
"poc",
(fun httpClient -> httpClient.BaseAddress <- Uri("https://example.com")))
|> ignore
```

Together with:
```
let factory = ctx.GetService()
let httpClient = factory.CreateClient("poc")
```

This does not work since the F#-compiler chooses another overload to be used, [the generic one](https://learn.microsoft.com/en-us/dotnet/api/microsoft.extensions.dependencyinjection.httpclientfactoryservicecollectionextensions.addhttpclient?view=dotnet-plat-ext-8.0#microsoft-extensions-dependencyinjection-hhttps://learn.microsoft.com/en-us/dotnet/api/microsoft.extensions.dependencyinjection.httpclientfactoryservicecollectionextensions.addhttpclient?view=dotnet-plat-ext-8.0#microsoft-extensions-dependencyinjection-httpclientfactoryservicecollectionextensions-addhttpclient-2(microsoft-extensions-dependencyinjection-iservicecollection-system-string-system-action((system-net-http-httpclient)))ttpclientfactoryservicecollectionextensions-addhttpclient-2(microsoft-extensions-dependencyinjection-iservicecollection-system-string-system-func((system-net-http-httpclient-system-iserviceprovider-1)))).

Here is a small application that illustrates the problem: https://github.com/aklefdal/FSharpNamedHttpClient

* How am I supposed register and use named HttpClients in F#?
* Do I have to use classes and constructor injection of dependencies to make HttpClientFactory work?
* Can I at least have warning issued from the compiler and possibly a way to force the compiler to use the right overload?

This issue is possibly related to
* https://github.com/dotnet/fsharp/issues/12957
* https://github.com/dotnet/fsharp/issues/11534

There is a workaround, and that is to add HttpClient as a generic argument to the call to AddHttpClient. This is not documented, nor do I know if it works in all cases. I don't even know why it works.

Update:
There is a second workaround, and that is explicitly to cast the second argument to `Action`.

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.