[英]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.尝试注入 Lazy 时出现以下错误。
It works fine without "Lazy<>"没有“Lazy<>”也能正常工作
I have registered it like below in startup.cs.我已经在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?任何想法,延迟初始化可能是什么问题?
Just don't use Lazy<IHttpClientFactory>
.只是不要使用
Lazy<IHttpClientFactory>
。 HttpClientFactory itself is the type that creates and caches instances of HttpClients, or rather, HttpClientHandlers. HttpClientFactory 本身是创建和缓存 HttpClients 或 HttpClientHandlers 实例的类型。
It's a singleton managed by the DI container itself so Lazy<IHttpClientFactory>
wouldn't have any effect, even if you got it to compile.它是一个由 DI 容器本身管理的单例,因此
Lazy<IHttpClientFactory>
不会产生任何影响,即使您编译它也是如此。
The source code of AddHttpClient explicitly registers a default HttpClientFactory as a singleton. 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.