0

HttpClient我每次提出请求时都会创建一个新的,但在互联网上搜索后,我发现这不是使用它的最佳方式。

我应该使用HttpClientFactory,但我寻找的每个网站都使用过ServiceCollection()IServiceCollection()类似:

var services = new ServiceCollection();
services.AddHttpClient()
var serviceProvider = services.BuildServiceProvider();

或者

public void ConfigureServices(.IserviceCollection services)
{
    services.addHttpClient(name, lambda expr);
}

当我尝试创建一个新的ServiceCollection时,Visual Studio 要求我创建一个类,那么如何HttpClientFactoryXamarin中实现?

编辑:我使用此链接进行实验,但我不知道如何将其合并到我的项目中:我有这样的东西:

class Database
{
    private static HttpClient client = new HttpClient();

    async public static Task<string> Some Request() {
        try {
            ...
            var response = await client.PostAsync(requestUrl, content);
            if (response.StatusCode == HttpStatusCode.OK)
            {
                return await response.Content.ReadAsStringAsync();
            }
            return ..
        }
        catch(...) {...}
    }
}

public static class Startup
{
    public static IServiceProvider ServiceProvider { get; set; }
    public static void Init()
    {
        //same thing as link without stream
    }
    static void ConfigureServices(HostBuilderContext ctx, IServiceCollection services)
    {
        services.AddHttpClient();
    }
4

1 回答 1

0

您确定已将Microsoft.Extensions.DependencyInjection nuget 添加到您的项目中并将其与

using Microsoft.Extensions.DependencyInjection;
于 2020-07-30T00:10:54.013 回答