[英]HttpClient with dependency injection in Azure function
Documentation says to use builder.Services.AddHttpClient()
for registration HttpClient but I can resolve HttpClient without this. 文档说使用
builder.Services.AddHttpClient()
来注册 HttpClient 但我可以在没有这个的情况下解析 HttpClient 。
I have a small startup where only register MyService:我有一个只注册 MyService 的小型初创公司:
public class Startup : FunctionsStartup
{
public override void Configure(IFunctionsHostBuilder builder)
{
builder.Services.AddTransient<MyService>();
}
}
and in Function, I want to resolve HttpClient and MyService and this code works.在 Function 中,我想解析 HttpClient 和 MyService 并且此代码有效。
public class Function
{
public Function(MyService service, HttpClient client)
{
}
[FunctionName("func")]
public async Task<IActionResult> Update(
[HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = null)]
HttpRequest request,
ILogger logger)
{
return new OkObjectResult("Hello");
}
}
builder.Services.AddHttpClient()
?builder.Services.AddHttpClient()
吗? Is this not redundant? You are right.你说的对。 You first need to register to it to the services:
您首先需要将其注册到服务:
public class Startup : FunctionsStartup
{
public override void Configure(IFunctionsHostBuilder builder)
{
//Register HttpClientFactory
builder.Services.AddHttpClient();
builder.Services.AddTransient<MyService>();
}
}
If your Service will use the HttpClientFactory it is important to be register before the service.如果您的服务将使用 HttpClientFactory,那么在服务之前进行注册很重要。 So when the MyService instance depedencies will be resolved there will already be a record for HttpCliendFactory in the DI container.
因此,当解决 MyService 实例依赖关系时,DI 容器中已经有 HttpCliendFactory 的记录。
Your Function.cs class will then be:您的 Function.cs class 将是:
public class Function
{
private IHttpClientFactory _httpClientFactory;
private MyService _myService;
public Function(MyService myService, IHttpClientFactory client)
{
_myService = myService;
_httpClientFactory = httpClientFactory;
}
[FunctionName("func")]
public async Task<IActionResult> Update(
[HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = null)]
HttpRequest request,
ILogger logger)
{
//How to use example
var client = _httpClientFactory.CreateClient();
return new OkObjectResult("Hello");
}
}
HttpClient of course can be used without the client factory, but if you spawn HttpClient objects from the HttpClientFactory you will have a better out of the box management of your HttpClient resources. HttpClient 当然可以在没有客户端工厂的情况下使用,但是如果您从 HttpClientFactory 生成 HttpClient 对象,您将对您的 HttpClient 资源进行更好的开箱即用管理。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.