You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.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容器正确解析并注入服务实例。

解决步骤

  1. 修改函数类,使用构造函数注入
    将依赖服务通过构造函数注入到函数类中,保存为私有字段后再在方法中使用:
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);
    }
}
  1. 检查Program.cs的DI配置语法
    确保服务注册代码没有语法错误,比如原代码中new MyConcreteClass(constructor args)的括号是否闭合,泛型的<>是否正确(原代码中的&lt;和&gt;是转义字符,实际代码中要写为<和>)。

内容的提问来源于stack exchange,提问作者user18901997

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 10:33:26