Reputation: 1214
When you add HttpClient using DI in Azure Functions it seems that anything that has a dependency on it must be a singleton, or the HttpClient will get disposed once the lifetime of the dependent class ends.
I'm adding HttpClient w/default settings:
builder.Services.AddHttpClient();
Here's the error I see in the logs when I attempt to re-run the function:
Cannot access a disposed object.
Object name: 'System.Net.Http.HttpClient'.
Can anyone confirm? If so, is this expected behavior?
Upvotes: 2
Views: 2500
Reputation: 18387
I am not sure if you had checked the official doc but here's how you should inject the http client factory into your code:
//registering
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 function
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
Upvotes: 4