Is my implementaton of HttpClient singleton appropriate? [closed]

丶灬走出姿态 提交于 2019-12-05 20:49:47

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/20074580/is-my-implementaton-of-httpclient-singleton-appropriate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!