我像这样注册HttpClient:
services.AddSingleton<HttpClient>();
然后在代码中进一步查找要依赖于此的另一个接口:
services.AddSingleton<IMyRepository>(
new MyRepository("<string>",
"<string>",
"<string>",
???,
logger));
所以我不确定在???中放什么。我可以输入“ new HttpClient()”,但这种方法无法实现注册HttpClient的目的。我基本上需要调用该方法来获取已添加的引用。想法?
谢谢。
答案 0 :(得分:4)
从服务提供商处解决该问题:
services.AddSingleton<IMyRepository>(serviceProvider =>
new MyRepository("<string>",
"<string>",
"<string>",
serviceProvider.GetRequiredService<HttpClient>(),
logger));
顺便说一句,您可能想使用HttpClientFactory(services.AddHttpClient();
)而不是services.AddSingleton<HttpClient>();
。
有关长期静态(或单例)HttpClient发生的DNS问题以及为什么应使用HttpClientFactory的信息,请参见You're (probably still) using HttpClient wrong and it is destabilizing your software。