【问题标题】:Access IMemoryCache service from AddHttpClient从 AddHttpClient 访问 IMemoryCache 服务
【发布时间】:2020-07-23 11:03:58
【问题描述】:

我正在使用 .NET Core 3.1。

在启动时,我添加以下内容:

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;
    });
}

问题是MyConfig是一个期望IMemoryCache的类:

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

证书从内存缓存中存储和加载。请问我该如何解决?

【问题讨论】:

  • “解决这个问题”到底是什么意思?获取用于加载证书的有效IMemoryCache 实例?
  • 是的,不知道如何“注入”它,因为我在控制器中使用类时通常会注入它。在启动中,我不太确定如何。谢谢

标签: c# asp.net-core httpclienthandler


【解决方案1】:

您可以使用通过ConfigurePrimaryHttpMessageHandler 重载传递的IServiceProvider 对象创建一个新的IMemoryCache 对象:

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

如果MyConfig作为服务注入,你也可以加载这个。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-03-25
    • 2021-11-14
    • 2019-06-02
    • 1970-01-01
    • 2022-07-20
    • 2018-08-27
    • 2014-10-01
    相关资源
    最近更新 更多