I'm trying to have a function that has its dependencies injected as outlined in documentation, Use dependency injection in .NET Azure Functions. My Startup class is defined as:
using System.Runtime.CompilerServices;
using Microsoft.Azure.Functions.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection;
[assembly: FunctionsStartup(typeof(MyFunctions.Startup))]
namespace MyFunctions{
public class Startup : FunctionsStartup
{
public override void Configure(IFunctionsHostBuilder builder)
{
builder.Services.AddHttpClient();
}
}
}
I set a breakpoint on the builder.Services.AddHttpClient()
statement to ensure the DI is configured.
Then I define my function using a HttpTrigger
:
using System;
using System.Net.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.Extensions.Logging;
namespace MyFunctions
{
public class ChangeProducer
{
private readonly HttpClient _httpClient;
public ChangeProducer(IHttpClientFactory httpClientFactory)
{
_httpClient = httpClientFactory.CreateClient();
}
[FunctionName("ChangeProducer")]
public void Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "Reservation")]HttpRequest request, ILogger log)
{
Console.WriteLine("foo");
}
}
}
When I run this from Visual Studio I hit the breakpoint in Startup.Configure
. Wonderful!
Then I change my function to use an EventGridTrigger
:
using System;
using System.Net.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.Extensions.Logging;
namespace MyFunctions
{
public class ChangeProducer
{
private readonly HttpClient _httpClient;
public ChangeProducer(IHttpClientFactory httpClientFactory)
{
_httpClient = httpClientFactory.CreateClient();
}
[FunctionName("ChangeProducer")]
public void Run([EventGridTrigger]EventGridEvent eventGridEvent, ILogger log)
{
Console.WriteLine("foo");
}
}
}
Once that change is made, and no other change, I don't hit the breakpoint in Startup.Configure
. Additionally, I know the DI is failing because when I try to invoke the function I get an error message that reads:
Executed 'ChangeProducer' (Failed, Id=06ae8b88-07c4-4150-91e5-8b88400aed72)
Microsoft.Extensions.DependencyInjection.Abstractions: Unable to resolve service for type 'System.Net.Http.IHttpClientFactory' while attempting to activate 'MyFunctions.ChangeProducer'.
Is there a known issue? I can't figure this out. The only difference is the trigger type.
Update 2019-06-24 - It's just the dependency injection
I want to be clear the issue is dependency injection isn't working, there isn't an issue with the EventGridTrigger
when the dependency on HttpClient
is not injected. Change the constructor to the following and the function works fine when triggered by the EventGridTrigger
:
public ChangeProducer()
{
_httpClient = new HttpClient();
}