Using a returned instance?

Issue

I have a hierarchy of classes that perform API requests. In the base class, I build the request object, and in some subclasses, this method is overridden.

Base class:

      protected virtual HttpRequestMessage BuildRequest(HttpMethod method, Uri uri, HttpContent content = null)
      {
           HttpRequestMessage request = new HttpRequestMessage(method, uri);
           if (null != content)
           {
                request.Content = content;
           }

           return request;
      }

Subclass:

      protected async override HttpRequestMessage BuildRequest(HttpMethod method, Uri uri, HttpContent content = null)
      {
           HttpRequestMessage request = await base.BuildRequest(method, uri, content);
           request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", AccessTokenHelper.GetAccessToken());

           return request;
      }

And then statements in other methods that consume the BuildRequest() method:

      using HttpRequestMessage request = BuildRequest(HttpMethod.Post, url, content);

As you can see, I’m using the returned instance. Will this also properly dispose of the HttpRequestMessage instances in each of the BuildRequest() methods? Or is this a classic memory leak situation after tens of thousands of requests?

Solution

If you look at the code, there’s a single instance created:

HttpRequestMessage request = new HttpRequestMessage(method, uri);

These other 2 lines only get the reference to the instance created above:

HttpRequestMessage request = await base.BuildRequest(method, uri, content);
using HttpRequestMessage request = BuildRequest(HttpMethod.Post, url, content);

So by using using HttpRequestMessage request = BuildRequest(HttpMethod.Post, url, content); you’re correctly disposing the instance created in the base BuildRequest method.

Answered By – Camilo Terevinto

Answer Checked By – Marilyn (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.