gpt4 book ai didi

azure - HttpClient 通过 Azure Functions 依赖注入(inject)进行处置

转载 作者:行者123 更新时间:2023-12-02 23:17:34 25 4
gpt4 key购买 nike

当您在 Azure Functions 中使用 DI 添加 HttpClient 时,似乎任何依赖它的东西都必须是单例,否则一旦依赖类的生命周期结束,HttpClient 将被释放。

我正在添加带有默认设置的 HttpClient:

builder.Services.AddHttpClient();

这是我尝试重新运行该函数时在日志中看到的错误:

Cannot access a disposed object.
Object name: 'System.Net.Http.HttpClient'.

有人可以证实吗?如果是这样,这是预期的行为吗?

最佳答案

我不确定您是否检查过官方文档,但以下是您应该如何将 http 客户端工厂注入(inject)代码中的方法:

//注册中

using System;
using Microsoft.Azure.Functions.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Http;
using Microsoft.Extensions.Logging;

[assembly: FunctionsStartup(typeof(MyNamespace.Startup))]

namespace MyNamespace
{
public class Startup : FunctionsStartup
{
public override void Configure(IFunctionsHostBuilder builder)
{
builder.Services.AddHttpClient();

builder.Services.AddSingleton((s) => {
return new MyService();
});

builder.Services.AddSingleton<ILoggerProvider, MyLoggerProvider>();
}
}
}

//azure 函数

using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;

namespace MyNamespace
{
public class HttpTrigger
{
private readonly IMyService _service;
private readonly HttpClient _client;

public HttpTrigger(IMyService service, IHttpClientFactory httpClientFactory)
{
_service = service;
_client = httpClientFactory.CreateClient();
}

[FunctionName("GetPosts")]
public async Task<IActionResult> Get(
[HttpTrigger(AuthorizationLevel.Function, "get", Route = "posts")] HttpRequest req,
ILogger log)
{
log.LogInformation("C# HTTP trigger function processed a request.");
var res = await _client.GetAsync("https://microsoft.com");
await _service.AddResponse(res);

return new OkResult();
}
}
}

https://learn.microsoft.com/en-us/azure/azure-functions/functions-dotnet-dependency-injection

关于azure - HttpClient 通过 Azure Functions 依赖注入(inject)进行处置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58922532/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com