在 Startup.cs 中键入客户端设置,无法获取注入服务中的信息
我有一个演示 Azure 功能并按如下方式设置类型化客户端: 但我无法在注入的 httpclient 实例中获取基地址。有什么建议吗?感谢
builder.Services.AddSingleton<IMyService, MyService>();//Comment out this line will make it work
builder.Services.AddHttpClient<IMyService, MyService>(client =>
{
client.BaseAddress = new Uri("https://api.github.com/");
});
}
public class MyService : IMyService
{
private readonly HttpClient httpClient;
public MyService(HttpClient httpClient)
{
this.httpClient = httpClient;
}
public async Task LogMsg()
{
Console.WriteLine(httpClient.BaseAddress);
}
更新: 删除 AddSignleton 行将起作用... 见评论里的链接
I have a demo Azure function and setup the typed client as follow:
But I can't get base address in injected httpclient instance. Any advice? Thanks
builder.Services.AddSingleton<IMyService, MyService>();//Comment out this line will make it work
builder.Services.AddHttpClient<IMyService, MyService>(client =>
{
client.BaseAddress = new Uri("https://api.github.com/");
});
}
public class MyService : IMyService
{
private readonly HttpClient httpClient;
public MyService(HttpClient httpClient)
{
this.httpClient = httpClient;
}
public async Task LogMsg()
{
Console.WriteLine(httpClient.BaseAddress);
}
Updates:
Remove the AddSignleton line will work...
See link in comment
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
尝试删除配置部分中的
AddSingleton()
注册。如果您想使用单例,请尝试将
HttpClientFactory
注入您的 Service 实例中,例如 (MyServiceshttp)。请参阅此处
Try to remove the
AddSingleton<MyServicehttp>()
Registration in Configuration Portion.If you want to use the singleton, try to inject
HttpClientFactory
inside your Service instance like (MyServiceshttp).Refer here