Reapping the HttpClient and life cycle of an ApiController

2

Based on on this site and also on I came to the conclusion that I should not use the class HttpClient in a using block even though it implements IDisposable . This would help reuse 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://pt.stackoverflow.com");
        // ...
    }
}

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

    
asked by anonymous 17.12.2018 / 16:49

1 answer

2

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

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

Already and would initialize 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 that instance of HttpClient that was initialized at the beginning of the application.

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