Pea Kay See Es
Pea Kay See Es

Reputation: 454

Access IMemoryCache service from AddHttpClient

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?

Upvotes: 1

Views: 512

Answers (1)

janw
janw

Reputation: 9646

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.

Upvotes: 3

Related Questions