c# – Reuse of HttpClient and lifecycle of an ApiController

Question:

Based on that site and also some answers from StackOverflow [en] I came to the conclusion that I shouldn't use the HttpClient class in a using block even though it implements IDisposable . This would help to reuse the object already instantiated and would 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://pt.stackoverflow.com");
        // ...
    }
}

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

Answer:

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

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

And do the initialization in _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 the inheritance of your Controllers to BaseApiController and you can use this instance of HttpClient that was started at the beginning of the application.

public class MyServiceController : BaseApiController
{
    public void Post()
    {
        // ...
        var result = await meuHttpClient.GetAsync("https://pt.stackoverflow.com");
        // ...
    }
}
Scroll to Top