~glorifiedgluer/gluer.org

ce670df9c52689b0ec420eafee4f95c1f7c1d1e6 — Victor Freire 5 months ago 0718409
article: standalone-ihttpclientfactory-without-asp-dot-net-s-dependency-injection
1 files changed, 33 insertions(+), 0 deletions(-)

M content-org/content.org
M content-org/content.org => content-org/content.org +33 -0
@@ 5200,6 5200,39 @@ Spaghetti al sugo.
Penne alla puttanesca.
#+end_image

** Standalone IHttpClientFactory without ASP.NET's Dependency Injection :dotnet:fsharp:
:PROPERTIES:
:EXPORT_DATE: 2023-06-28
:EXPORT_FILE_NAME: standalone-ihttpclientfactory-without-asp-dot-net-s-dependency-injection
:EXPORT_HUGO_SLUG: standalone-ihttpclientfactory-without-asp-dot-net-s-dependency-injection
:END:

#+begin_description
Using the IHttpClientFactory without ASP.NET's dependency injection.
#+end_description

Sometimes you don't want to use [[https://learn.microsoft.com/en-us/aspnet/core/fundamentals/dependency-injection][ASP.NET's Dependency Injection]], in
some of these cases, you can get away by using other forms of
dependency injection (specially in F#). However, one of the things
that I always missed was the [[https://learn.microsoft.com/en-us/dotnet/api/system.net.http.ihttpclientfactory][IHttpClientFactory]] interface.

The HttpClient injected by ASP.NET manages a lot for you, ranging from
DNS changes to thread-safety. Here's how you can use without ASP.NET's
services:

#+begin_src fsharp
open Microsoft.AspNetCore.Builder
open Microsoft.Extensions.DependencyInjection

let builder = Host.CreateApplicationBuilder()

let serviceProvider = ServiceCollection().AddHttpClient().BuildServiceProvider();
let factory = serviceProvider.GetService<IHttpClientFactory>();

// usage example
let client = factory.CreateClient()
#+end_src

* Footnotes

[fn:45] Fun fact: I introduced the dotnet module on devenv!