我找到了这位演员:
public class MobileOtpService : IMobileOptService
{
private readonly HttpClient _client;
public MobileOtpService(HttpClient client) // How is this injected?
{
_client = client;
}
}
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddScoped<IMobileOptService, MobileOtpService>();
...
services.AddHttpClient();
}
}
我找不到
MobileOtpService
的任何硬编码实例,所以它一定只是使用 DI。
HttpClient
是如何注射的?
这是因为
services.AddHttpClient()
自动发生的吗?
我找不到任何设置
BaseAddress
等的代码。
当您在扩展方法中使用
services.AddHttpClient();
时,您会看到它们添加了默认的 HttpClient
,如下所示:
// Register default client as HttpClient
services.TryAddTransient(s =>
{
return s.GetRequiredService<IHttpClientFactory>().CreateClient(string.Empty);
});
对于您的注册
MobileOtpService
,我建议使用扩展方法AddHttpClient
,如下所示:
services.AddHttpClient<IMobileOtpService,MobileOtpService>(httpClient =>
{
httpclient.BaseAddress = "localhost"
// add other httpclient config here
});