是我的HttpClient单身的implementaton合适? [英] Is my implementaton of HttpClient singleton appropriate?

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

问题描述

我在我的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单身的implementaton合适?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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