.NET 7独立进程Azure Functions依赖注入失效引发空引用异常
.NET7独立进程Azure Functions依赖注入失效问题解决
问题背景
运行基于.NET7的独立进程Azure Functions,使用以下稳定包版本:
- Microsoft.Azure.Functions.Extensions (1.1.0)
- Microsoft.Azure.Functions.Worker (1.10.1)
- Microsoft.Azure.Functions.Worker.Sdk (1.7.0)
按官方指南配置依赖注入后,函数执行时抛出空引用异常。相关代码如下:
Program.cs配置代码
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();
函数代码
public class MyAzureFunction { [Function("MyAzureFunction")] public async Task RunAsync([ATrigger( ...TheTriggerArgs... )] IReadOnlyList<MyDataClass> input, IMyInterface myService) { myService.DoSomeWork(input); // 此处抛出System.NullReferenceException } }
执行时抛出异常:
System.NullReferenceException: Object reference not set to an instance of an object.
该依赖注入模式在Minimal API、Blazor等项目中正常运行,尝试重写启动方法的方式也无效。
问题原因
独立进程模式(Isolated Worker)的Azure Functions不支持在函数方法的参数中直接注入依赖服务,方法参数仅用于绑定触发器、输入/输出绑定项。只有通过构造函数注入的方式,才能让DI容器正确解析并注入服务实例。
解决步骤
- 修改函数类,使用构造函数注入
将依赖服务通过构造函数注入到函数类中,保存为私有字段后再在方法中使用:
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); } }
- 检查Program.cs的DI配置语法
确保服务注册代码没有语法错误,比如原代码中new MyConcreteClass(constructor args)的括号是否闭合,泛型的<>是否正确(原代码中的<和>是转义字符,实际代码中要写为<和>)。
内容的提问来源于stack exchange,提问作者user18901997
相关产品推荐
相关产品推荐

