带有Azure函数依赖注入的HttpClient被处置

时间:2019-11-18 20:36:53

标签: azure azure-functions

当您在Azure Functions中使用DI添加HttpClient时,似乎所有与之依赖的东西都必须是单例,否则一旦依赖类的生命周期结束,HttpClient将被处置。

我要添加具有默认设置的HttpClient:

<custom-element class="red" id="ce1"></custom-element>
<custom-element class="green border"></custom-element>

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

builder.Services.AddHttpClient();

任何人都可以确认吗?如果是这样,这是预期的行为吗?

1 个答案:

答案 0 :(得分:3)

我不确定您是否检查了官方文档,但是这是将http客户端工厂注入代码中的方法:

//注册

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>();
        }
    }
}

//天蓝色功能

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://docs.microsoft.com/en-us/azure/azure-functions/functions-dotnet-dependency-injection