Httpclient reuse and an Apicontroller lifecycle

Asked

Viewed 66 times

3

Based on that website and also in some answers from Stackoverflow [en] I came to the conclusion that I shouldn’t use the class HttpClient in a block using despite the same implement IDisposable. This would help in the reuse of the already instantiated object and bring performance improvements among others.

But consider the following code snippet:

public class MyServiceController : ApiController
{
    private static HttpClient _httpClient = new HttpClient();

    public void Post()
    {
        // ...
        var result = await _httpClient.GetAsync("https://answall.com");
        // ...
    }
}

My API is consuming another service, but if when we talk about the life cycle of MyServiceController, there would be no reuse since each request of the Post will create a new instance of the class, correct? In that case I could implement normally using the block using?

  • If you make it public and start at startup

  • 3

    @Leandroangelo thanks for your comment. Leaving the HttpClient class audience startup could not bring me trouble if MyServiceController receive many simultaneous requests?

1 answer

2

I would create a BaseApiController abstract inheriting the ApiController and add the HttpClient as an audience there

public  abstract class BaseApiController : ApiController
{
    public static HttpClient meuHttpClient { get; set; }
}

And would do the boot on _Application_Start() of Global.asax.Cs

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();
    GlobalConfiguration.Configure(WebApiConfig.Register);
    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
    RouteConfig.RegisterRoutes(RouteTable.Routes);
    BundleConfig.RegisterBundles(BundleTable.Bundles);

    BaseApiController.meuHttpClient = new System.Net.Http.HttpClient();
}

So you change your inheritance Controllers to the BaseApiController and you can use that instance of the Httpclient that was initialized at the beginning of the application.

public class MyServiceController : BaseApiController
{
    public void Post()
    {
        // ...
        var result = await meuHttpClient.GetAsync("https://answall.com");
        // ...
    }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.