title: How to use ConfigurePrimaryHttpMessageHandler generic
body: <p>I want to add an HttClientHandler for a Typed HttpClient in order to include certificate authentication.</p>
  
  <p>All the examples I'm finding on the internet are like this:</p>
  
  <pre><code>services.AddHttpClient&lt;IMyService, MyService&gt;()
      .ConfigurePrimaryHttpMessageHandler(() =&gt;
      {
          return new HttpClientHandler()
          {
              // Set here whatever you need to get configured
          };
      });
  </code></pre>
  
  <p>But I don't want to include all the logic to obtain the certificate here, so I would like to use the generic version of <strong>ConfigurePrimaryHttpMessageHandler&lt;></strong> and write my own message handler to include the certificate in the request.</p>
  
  <p>The problem is that I'm struggling to understand how should I implement the message handler... should I inherit from <strong>HttpClientHandler</strong> ??</p>
  
  <p>Help, please!</p>
  
  <p><strong>Update</strong></p>
  
  <p>As I initially suspected, and @Nkosi confirmed, to derive from HttpClient handler is the way to go in this scenario. The code in the ends looks similar to this:</p>
  
  <pre><code>public class MyHttpClientHandler : HttpClientHandler
  {
      private readonly IMyConfiguration _myConfiguration;
  
      public MyHttpClientHandler(IMyConfiguration myConfiguration)
      {
          _myConfiguration = myConfiguration;
  
          using (var certStore = new X509Store(StoreName.My, StoreLocation.LocalMachine))
          {
              certStore.Open(OpenFlags.ReadOnly);
              var certCollection = certStore.Certificates.Find(
                  X509FindType.FindBySerialNumber,
                  _myConfiguration.MyCertificateSerial,
                  true);
  
              X509Certificate2 certificate = certCollection[0];    
              ClientCertificateOptions = ClientCertificateOption.Manual;
              SslProtocols = System.Security.Authentication.SslProtocols.Tls12;
              ClientCertificates.Add(certificate);
          }
      }
  }
  </code></pre>
  
  <p><strong>Very important!</strong></p>
  
  <p>On the other hand while trying to register my http client handler I noticed it was never being called. After some googling I found out that currently there's an open bug about that (<a href="https://github.com/aspnet/Extensions/issues/851" rel="noreferrer">https://github.com/aspnet/Extensions/issues/851</a>). So until it get's fixed you need configure your handler this way:</p>
  
  <pre><code>services.AddTransient&lt;MyHttpClientHandler&gt;();
  
  services.AddHttpClient&lt;IMyService, MyService&gt;()
      .ConfigurePrimaryHttpMessageHandler(sp =&gt; sp.GetRequiredService&lt;MyHttpClientHandler&gt;());
  </code></pre>