Good news everyone, the .NET 4.5 HttpClient is thread safe!
This means that you can share instances of your HttpClients across your entire application. This is useful in that it allows you to reuse persisted connections. One of the best ways to do this is to create a class that can manage the object lifetime of those clients for you.
Below is a simple HttpClientManager that will create one HttpClient per authority. Why per authority? Because you might have to have different settings or credentials for different websites.
Sample Unit Tests
public class HttpClientManagerTests
{
[Fact]
public void GetForAuthority()
{
using (var manager = new HttpClientManager())
{
var client1 = manager.GetForAuthority("http://tomdupont.net/");
var client2 = manager.GetForAuthority("https://tomdupont.net/");
Assert.Same(client1, client2);
var client3 = manager.GetForAuthority("http://google.com/");
Assert.NotSame(client1, client3);
}
}
[Fact]
public void TryRemoveForAuthority()
{
const string uri = "http://tomdupont.net/";
using (var manager = new HttpClientManager())
{
Assert.False(manager.TryRemoveForAuthority(uri));
manager.GetForAuthority(uri);
Assert.True(manager.TryRemoveForAuthority(uri));
}
}
}