1

I am using .NET Core 3.1.

On Startup, I am adding the following:

public void ConfigureServices(IServiceCollection services)
{
    services.AddHttpClient<IApns, Apns>().ConfigurePrimaryHttpMessageHandler(() =>
    {
        var handler = new HttpClientHandler { SslProtocols = SslProtocols.Tls12 };

        // How do I access memory cache (MyConfig expect it) - normally I use it injected. 
        var certificate = new MyConfig(...).GetCertificate 

        handler.ClientCertificates.Add(certificate);
        return handler;
    });
}

The problem is MyConfig is a class that expects IMemoryCache:

public MyConfig(IMemoryCache cache)
{
    _cache = cache;
}

The certificate is stored and loaded from memory cache. How do I get around this please?

janw
  • 8,758
  • 11
  • 40
  • 62
PKCS12
  • 407
  • 15
  • 41
  • What do you mean exactly by "get around this"? Get a valid `IMemoryCache` instance for loading the certificate? – janw Jul 23 '20 at 11:11
  • 1
    Yeah, not sure how to "inject it" as normally it is injected when I use the class in the controller. In Startup, I am not so sure how. Thanks – PKCS12 Jul 23 '20 at 11:15

1 Answers1

3

You can create a new IMemoryCache object by using the IServiceProvider object which is passed through an overload of ConfigurePrimaryHttpMessageHandler:

services.AddHttpClient<IApns, Apns>().ConfigurePrimaryHttpMessageHandler((serviceProvider) =>
{
    var memoryCache = serviceProvider.GetService<IMemoryCache>();
    
    var certificate = new MyConfig(memoryCache).GetCertificate();
    // ...
}

If MyConfig is injected as a service, you can also load this one instead.

janw
  • 8,758
  • 11
  • 40
  • 62