简体   繁体   中英

How to create one instance of Httpclient in Xamarin Forms

是否可以在OnStart() Xamarin Forms 应用程序中创建一个httpclient实例并在我的应用程序中的任何地方使用它?

Yes you can use the same httpclient for all request in your app. But you will need to take note that if there is API that is having different base URL or headers information, then you will need to create another httpclient for that.

What I do is I have a class to manage the HttpClient instances. If there is no instance that is matching the HttpConfig, it will create and store it. If there is already an existing instance, it will just return it.

Example of code (HttpService is dependency injected):

public class HttpService : IHttpService
{
    private static readonly int MAX_CLIENT = 5;

    private Dictionary<HttpConfig, HttpClient> mClients;
    private Queue<HttpConfig> mClientSequence;

    public HttpService()
    {
        mClients = new Dictionary<HttpConfig, HttpClient>();
        mClientSequence = new Queue<HttpConfig>();
    }

    private HttpClient CreateHttpClientAsync(HttpConfig config)
    {
        HttpClient httpClient;

        if (mClients.ContainsKey(config))
        {
            httpClient = mClients[config];
        }
        else
        {
            // TODO: Create HttpClient...

            if (mClientSequence.Count >= MAX_CLIENT)
            {
                // Remove the first item
                var removingConfig = mClientSequence.Dequeue();
                mClients.Remove(removingConfig);
            }

            mClients[config] = httpClient;
            mClientSequence.Enqueue(config);
        }

        return httpClient;
    }
...
}

HttpConfig is class where I store BaseUrl, Timeout, Headers, Auth info, etc. You will need to override the Equals method in the class for comparison whether there is existing same config.

public override bool Equals(object obj)
{
    // Logic to determine whether it is same config
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM