I am using System.Net.HttpClient (.Net 4.5) in my MVC4 project. I know that a single instance of HttpClient can be used for all Http requests across the web app. Here is my implementation of the HttpClient singleton which should return the single instance every time.
public sealed class HttpClientInstance: HttpClient
{
// singleton instance
private static readonly HttpClientInstance instance = new HttpClientInstance();
static HttpClientInstance() { }
private HttpClientInstance() : base() {
Timeout = TimeSpan.FromMilliseconds(15000)));
}
/// <summary>
/// Returns the singleton instance of HttpClient
/// </summary>
public static HttpClient Instance
{
get
{
return instance;
}
}
}
Do you see any issues with this?
I know I could possibly use Ninject to inject the dependency in singleton scope but that is besides the point.
There are a few properties that you cannot change after you have made the first request. I think timeout might be one of them, so be aware of that.
You also need to be careful that individual requests don't mess with the DefaultRequestHeaders as that could confuse other requests.
It is always a good idea to try and share HttpClient instances. Creating a singleton is an extreme case of that but with care it should work just fine for you.