将Singleton HttpClient与Microsoft.Rest.ServiceClient一起使用-获取System.MissingMethodException

时间:2018-10-09 20:23:29

标签: c# azure httpclient

我正在尝试对我的Azure API客户端进行重做,以对HttpClient使用单例ServiceClient<T>,因为建议使用多个来源(出于性能考虑,对于HttpClient也建议使用此方法Microsoft.Rest.ServiceClient(通常)在幕后使用)

我正在使用Microsoft.Rest.ClientRuntime.2.3.12版本

我看到Microsoft.Rest.ServiceClient具有用于重用HttpClient

的构造函数
protected ServiceClient(HttpClient httpClient, bool disposeHttpClient = true);

这是我的API客户端的构造函数,用于重用 HttpClient,但是在调用它时会失败,并显示System.MissingMethodException Void Microsoft.Rest.ServiceClient`1。 ctor(System.Net.Http.HttpClient,布尔)

public MyAPIclient(ServiceClientCredentials credentials, HttpClient client) 
    : base(client, disposeHttpClient: false)
{
    this._baseUri = new Uri("https://...");
    if (credentials == null)
    {
        throw new ArgumentNullException("credentials");
    }
    this.Credentials = credentials;
    Credentials?.InitializeServiceClient(this);
}

这就是我调用API客户端的方式

using (var apiClient = new MyAPIclient(credentials, HttpClientSingleton.Client)) 
//I get Method not found 'Void Microsoft.Rest.ServiceClient`1..ctor(System.Net.Http.HttpClient, Boolean)'
{
    //some api call
}

这是我实例化我的http客户端单例的方式

public static class HttpClientSingleton
{
    public static readonly HttpClient Client = new HttpClient() { Timeout = TimeSpan.FromMinutes(30) };
}

为什么会出现此异常(我看到ServiceClient ctor(httpClient, bool))?

如何解决此问题?

1 个答案:

答案 0 :(得分:1)

就像Nkosi所说的那样,您应该尝试还原nuget软件包,清除obj / bin并重建。这通常在事情变得步履蹒跚时发生。随着所有的阴影缓存等,事情可能最终不匹配。我根据您的代码创建了一个小示例,它没有任何问题。如果发现仍然无法使用,则应在文件中包含更多信息,例如类声明和using语句,以及所使用的.net版本。

以下内容对我来说适用于4.5.2 ServiceClient 2.3.12

using Microsoft.Rest;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp2
{
class Program
{
    static void Main(string[] args)
    {
        using (var apiClient = new MyAPIclient(null, HttpClientSingleton.Client))
        //I get Method not found 'Void Microsoft.Rest.ServiceClient`1..ctor(System.Net.Http.HttpClient, Boolean)'
        {
            var httpClient = apiClient.HttpClient;
        }
    }

    public class MyAPIclient : ServiceClient<MyAPIclient>
    {
        protected Uri _baseUri { get; set; }
        protected ServiceClientCredentials Credentials { get; set; }

        public MyAPIclient(ServiceClientCredentials credentials, HttpClient client) : base(client, disposeHttpClient: false)
        {
            this._baseUri = new Uri("https://stackoverflow.com");
            this.Credentials = credentials;
            if(credentials != null)
                Credentials?.InitializeServiceClient(this);
        }
    }

    public static class HttpClientSingleton
    {
        public static readonly HttpClient Client = new HttpClient() { Timeout = TimeSpan.FromMinutes(30) };
    }

}
}