在 Startup.cs 中键入客户端设置,无法在注入的服务中获取信息
typed client setup in Startup.cs, cannot get info in injected service
我有一个演示 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 行将起作用...
见评论link
can't get the base address in injected httpclient instance
尝试删除配置部分中的 AddSingleton<MyServicehttp>()
注册。
public class Startup : FunctionsStartup
{
public override void Configure(IFunctionsHostBuilder builder)
{
builder.Services.AddScoped<MyService>();
builder.Services.AddScoped<Customlog>();
//Removed AddSingleton in service registration
//builder.Services.AddSingleton<MyServiceshttp>()
builder.Services.AddHttpClient<MyServicehttp>(client =>
{
// this code never runs
client.BaseAddress = new Uri("https://api.github.com/");
});
}
}
如果您想使用单例,请尝试在您的服务实例中注入 HttpClientFactory
,例如 (MyServiceshttp).
参考here
我有一个演示 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 行将起作用... 见评论link
can't get the base address in injected httpclient instance
尝试删除配置部分中的 AddSingleton<MyServicehttp>()
注册。
public class Startup : FunctionsStartup
{
public override void Configure(IFunctionsHostBuilder builder)
{
builder.Services.AddScoped<MyService>();
builder.Services.AddScoped<Customlog>();
//Removed AddSingleton in service registration
//builder.Services.AddSingleton<MyServiceshttp>()
builder.Services.AddHttpClient<MyServicehttp>(client =>
{
// this code never runs
client.BaseAddress = new Uri("https://api.github.com/");
});
}
}
如果您想使用单例,请尝试在您的服务实例中注入 HttpClientFactory
,例如 (MyServiceshttp).
参考here