0

I create a new HttpClient every time I made a request but after searching on the internet I found that is not the best way to use it.

I should use HttpClientFactory but every website where I look for, has it used with ServiceCollection() or IServiceCollection() like :

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

or

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

When I try to create a new ServiceCollection, Visual Studio asks me to create a class, so how can I implement HttpClientFactory in Xamarin?

Edit : I use this link for experimentation but i don't know how to incorporate in my project : I have something like this :

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();
    }
toto
  • 1
  • 1
  • 3
  • Try this way if you use Prism: https://stackoverflow.com/questions/63803919/addrefitclient-dryioc-and-iserviceprovider-on-prism-for-xamarin-forms/68068850#68068850 – ledragon Jun 21 '21 at 13:50

1 Answers1

-1

Are you sure you have added the Microsoft.Extensions.DependencyInjection nuget to your project and used it with

using Microsoft.Extensions.DependencyInjection;
Peter Csala
  • 17,736
  • 16
  • 35
  • 75
  • nope but i forgot to add some package following this [link](https://montemagno.com/add-asp-net-cores-dependency-injection-into-xamarin-apps-with-hostbuilder/) – toto Jul 30 '20 at 07:58
  • but the dependencyInjection is a weird thing for me, I never use it before so i don't know yet how I can use it on my project, because the class that take care of Database Request are static (all the methods are static) so if call one time to initialize my `HttpClient` field so is it the same thing as a singleton `HttpClient` with DNS issues ? – toto Jul 30 '20 at 08:10