HttpClient single instance with different authentication headers
<p>Given that the .net HttpClient has been designed with reuse in mind and is intended to be <a href="http://chimera.labs.oreilly.com/books/1234000001708/ch14.html" rel="noreferrer">long lived</a> and <a href="https://stackoverflow.com/questions/14075026/httpclient-crawling-results-in-memory-leak">memory leaks have been reported</a> in short lived instances. What guide lines are there where you want to make restful calls to a given endpoint using different bearer tokens (or any authorization header) when calling the endpoint for multiple users?</p>

<pre><code>private void CallEndpoint(string resourceId, string bearerToken) {
  httpClient.DefaultRequestHeaders.Authorization =
    new AuthenticationHeaderValue(&quot;bearer&quot;, bearerToken);
  var response = await httpClient.GetAsync($&quot;resource/{resourceid}&quot;);
}
</code></pre>
<p>Given the above code could be called by any number of threads on a web application it is easily possible that the header set in the first line is not the same one that is used when calling the resource.</p>
<p>Without causing contention using locks and maintaining a stateless web application what is the recommended approach to creating and disposing HttpClients for a single endpoint (My current practice is to create a single client per endpoint)?</p>
<hr />
<blockquote>
<p><strong>Lifecycle</strong></p>
<p>Although HttpClient does indirectly implement the IDisposable
interface, the recommended usage of HttpClient is not to dispose of it
after every request. The HttpClient object is intended to live for as
long as your application needs to make HTTP requests. Having an object
exist across multiple requests enables a place for setting
DefaultRequestHeaders and prevents you from having to respecify things
like CredentialCache and CookieContainer on every request, as was
necessary with HttpWebRequest.</p>
</blockquote>