我对 HttpClient 单例的实现是否合适? [英] Is my implementaton of HttpClient singleton appropriate?

查看:42
本文介绍了我对 HttpClient 单例的实现是否合适?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的 MVC4 项目中使用 System.Net.HttpClient (.Net 4.5).我知道 HttpClient 的单个实例可用于整个 Web 应用程序的所有 Http 请求.这是我对 HttpClient 单例的实现,它应该每次都返回单个实例.

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?

我知道我可以使用 Ninject 在单例范围内注入依赖项,但这不是重点.

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.

您还需要注意个别请求不要与 DefaultRequestHeaders 混淆,因为这可能会混淆其他请求.

You also need to be careful that individual requests don't mess with the DefaultRequestHeaders as that could confuse other requests.

尝试和共享 HttpClient 实例总是一个好主意.创建单例是这种情况的一个极端情况,但要小心,它应该适合您.

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.

这篇关于我对 HttpClient 单例的实现是否合适?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆