Dependency Injection in .Net Azure Function Isolated Process

I have an Azure Function running .Net 7 isolated, including the latest stable versions of:

  • Microsoft.Azure.Functions.Extensions (1.1.0)

  • Microsoft.Azure.Functions.Worker (1.10.1)

  • Microsoft.Azure.Functions.Worker.Sdk (1.7.0)

I am following this dependency injection guide specific to isolated functions, and am having some trouble getting it working:

https://learn.microsoft.com/en-us/azure/azure-functions/dotnet-isolated-process-guide#start-up-and-configuration

My Program.cs contains this for injecting the dependency:

using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

var host = new HostBuilder()
    .ConfigureFunctionsWorkerDefaults()
    .ConfigureServices(s => 
    {
        s.AddSingleton<IMyInterface>(new MyConcreteClass(constructor args);
    })
    .Build();

await host.RunAsync();

And then in the Azure function code:

public class MyAzureFunction
{
    [Function("MyAzureFunction")]
    public async Task RunAsync([ATrigger(
        ...TheTriggerArgs...
    )] IReadOnlyList<MyDataClass> input, IMyInterface myService)
    {
        myService.DoSomeWork(input); //exception is thrown here
    }
}

There are no compiler warnings in VS, but a null reference exception is thrown when the function executes the commented line.

The error: "System.NullReferenceException: ‘Object reference not set to an instance of an object.’"

It seems the dependency injection is simply not working…

The exact same pattern and classes work fine for me in other apps like minimal API’s and Blazor Apps, so I think this is something specific to Azure Functions?

If it makes any difference, I’ve also tried doing Azure Function dependency injection the "other" way (with a start method override) with the same result: https://learn.microsoft.com/en-us/azure/azure-functions/functions-dotnet-dependency-injection

>Solution :

Have you tried like the following code:

public class MyAzureFunction
{
private readonly IMyInterface _myService;

public MyAzureFunction(IMyInterface myService){
_myService = myService;
}
    [Function("MyAzureFunction")]
    public async Task RunAsync([ATrigger(
        ...TheTriggerArgs...
    )] IReadOnlyList<MyDataClass> input)
    {
        _myService .DoSomeWork(input);
    }
}

Leave a Reply