Home > Blockchain >  One httpClient for many method in one class
One httpClient for many method in one class

Time:02-11

I would like to use one httpclient to many method in class. Below is the simplified code:

public class test{

private readonly HttpClient _httpClient;

public Test(){
_httpClient = new HttpClient();
}

public void method1(){
using (_httpClient){
//...
}
}

public void method2(){
using (_httpClient){
//...
}
}

public void method3(){
using (_httpClient){
//...
}
}
}

Then it calls the method data:

public async static void TestHttpClient()
        {
            Test test1 = new Test();
            test1.Method1();
            test1.Method2();
            test1.Method3();
        }

Method 1 is working. When calling the second one I get the message: "You cannot access a deleted object."

Thanks for helps.

Regards

CodePudding user response:

using calls the Dispose() method after the scope - which destroys the object - keep the instance of your HttpClient within the instance of your object

public class test : IDisposable
{
    private readonly HttpClient _httpClient;
    public test()
    {
        _httpClient = new HttpClient();
    }

    public void Dispose()
    {
        _httpClient.Dispose();
    }

    public void method1()
    {
        //...
    }
}

then you can dispose your object instead of the HttpClient

using(test myObject = new test()) 
{
    myObject.method1();
    myObject.method2();
}

CodePudding user response:

If you want Test to create and reuse a disposable resource (e.g. HttpClient, then Test should implement IDisposable and should dispose of the resource in its Dispose method. That means that the class using Test should use a using block:

public async static void TestHttpClient()
{
    using (Test test1 = new Test())
    {   
        test1.Method1();
        test1.Method2();
        test1.Method3();
    }
}

CodePudding user response:

One way to do it is to create a private variable and a get accessor

    private HttpClient _httpClient;
    
    private HttpClient MyClient 
    {
        get {
            if (_httpClient == null)
            {
                _httpClient = new HttpClient
                {
                    BaseAddress = new Uri($"https://your.url/")
                };
                //Other client logic goes here
            }                
            return _httpClient;
        }
    }

Then from your method, you just reference the accessor

public async Task method1()
{
    await MyClient.Post() //post logic here
   //...
}

You don't need to dispose HttpClient, MS recommends leaving the object in place, unless you know you need to forcibly close the connection.

  •  Tags:  
  • c#
  • Related