嘗試注入 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'.'
任何想法,延遲初始化可能是什么問題?
uj5u.com熱心網友回復:
只是不要使用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>();
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/344047.html
標籤:C# 。网 asp.net核心 依赖注入 dotnet-httpclient
