Search code examples
c#.netasp.net-coredependency-injectiondotnet-httpclient

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


I am getting the below error while trying to inject Lazy.

It works fine without "Lazy<>"

I have registered it like below in startup.cs.

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

        ..
   }

I am trying to inject it in a controller like below:

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

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

Here, I am getting an error:

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

Any idea, what could be the issue in lazy initialization?


Solution

  • Just don't use Lazy<IHttpClientFactory>. HttpClientFactory itself is the type that creates and caches instances of HttpClients, or rather, HttpClientHandlers.

    It's a singletonmanaged by the DI container itself so Lazy<IHttpClientFactory> wouldn't have any effect, even if you got it to compile.

    The source code of AddHttpClient explicitly registers a default HttpClientFactory as a singleton.

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