![](/img/trans.png)
[英]There is no registered service of type '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.