繁体   English   中英

尝试激活服务时无法解析类型“System.Lazy`1[System.Net.Http.IHttpClientFactory]”的服务

[英]Unable to resolve service for type 'System.Lazy`1[System.Net.Http.IHttpClientFactory]' while attempting to activate service

尝试注入 Lazy 时出现以下错误。

没有“Lazy<>”也能正常工作

我已经在startup.cs中注册了它,如下所示。

 public void ConfigureServices(IServiceCollection services)
    {
        services.AddHttpClient();
        ..

        ..
   }

我正在尝试将它注入到如下所示的控制器中:

 private readonly Lazy<IHttpClientFactory> _clientFactory;
    protected IHttpClientFactory ClientFactory => _clientFactory.Value;

    public ValuesController(Lazy<IHttpClientFactory> clientFactory)
    {
         _clientFactory = clientFactory;
    }

在这里,我收到一个错误:

System.InvalidOperationException: 'Unable to resolve service for type 'System.Lazy`1[System.Net.Http.IHttpClientFactory]' while attempting to activate 'POC.Core.Controllers.ValuesController'.'

任何想法,延迟初始化可能是什么问题?

只是不要使用Lazy<IHttpClientFactory> HttpClientFactory 本身是创建和缓存 HttpClients 或 HttpClientHandlers 实例的类型。

它是一个由 DI 容器本身管理的单例,因此Lazy<IHttpClientFactory>不会产生任何影响,即使您编译它也是如此。

AddHttpClient的源代码显式地将默认 HttpClientFactory 注册为单例。

    public static IServiceCollection AddHttpClient(this IServiceCollection services)
    {
        if (services == null)
        {
            throw new ArgumentNullException(nameof(services));
        }

        services.AddLogging();
        services.AddOptions();

        //
        // Core abstractions
        //
        services.TryAddTransient<HttpMessageHandlerBuilder, DefaultHttpMessageHandlerBuilder>();
        services.TryAddSingleton<DefaultHttpClientFactory>();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM