Home > .NET Core, C#, WPF > Using HttpClientFactory with WPF on .NET Core 3.0

Using HttpClientFactory with WPF on .NET Core 3.0

In the last post, we talked about how to use Dependency Injection with WPF applications running on .NET 3.0. We saw that with .NET Core 3.0 we can use the same approach that we are accustomed to when working with ASP.NET Core.

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

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:

private void ConfigureServices(IServiceCollection services)
{
    // ...

    services.AddHttpClient();

    services.AddTransient(typeof(MainWindow));
}

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:

private readonly IHttpClientFactory httpClientFactory;

public MainWindow(IHttpClientFactory httpClientFactory)
{
    InitializeComponent();

    this.httpClientFactory = httpClientFactory;
}

In this way, when we need an HttpClient, we just need to retrieve it from the factory, as usual:

private async void Button_Click(object sender, RoutedEventArgs e)
{
    var client = httpClientFactory.CreateClient();
    var response = await client.GetStringAsync
                         ("https://marcominerva.wordpress.com/feed/");
    
    // ...
}

That’s it. That simple. If you want to read a great article that explains why we should always use HttpClientFactory, take a look to HttpClient Creation and Disposal Internals: Should I Dispose of HttpClient? by Steve Gordon.

Advertisements
Categories: .NET Core, C#, WPF

Leave a comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: