An interesting feature that we typically use with ASP.NET Core is the HttpClientFactory: it is a factory, available since .NET Core 2.1, for creating HttpClient instances to be used in our applications. Also in this case, we can use the same pattern within a WPF application running on .NET Core 3.0.

Let’s start from the sample we created in the last post. First of all, we need to add the Microsoft.Extensions.Http NuGet package (as always, remember to select the Include prerelease check):

Adding Microsoft.Extensions.Http NuGet package to WPF application

Then, we need to register the HttpClientFactory. Let’s do it in the ConfigureServices method of App.xaml.cs:

There are multiple way to use the HttpClientFactory. At line 5 we can see the simplest approach: using the AddHttpClient extension method we register a default HttpClientFactory from which we can get the actual HttpClient when we need it.

So, for example in the constructor of MainWindow we pass a reference to it: