9

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.

dotnetster
  • 1,601
  • 1
  • 16
  • 19
  • 4
    Working code should probably be moved to [Code Review](http://codereview.stackexchange.com) – crthompson Nov 19 '13 at 14:48
  • 1
    According to this http://msdn.microsoft.com/pl-pl/library/system.net.http.httpclient%28v=vs.110%29.aspx instance members are not guaranteed to be thread safe. Are you sure you won't hit the concurrency issues? – Wiktor Zychla Nov 19 '13 at 14:50
  • 2
    @WiktorZychla - HttpClient acts as a session for all HTTP requests. Also, all methods for HTTP operations are thread-safe as mentioned in the same link you provided. – dotnetster Nov 19 '13 at 14:55

1 Answers1

3

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.

Darrel Miller
  • 139,164
  • 32
  • 194
  • 243