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

本地运行Azure Function时WebJobsBuilderExtensions引发StackOverflowException

Azure Function本地运行触发StackOverflowException

本地运行Azure Function时,在Microsoft.Azure.WebJobs命名空间下WebJobsBuilderExtensions类的如下代码行抛出StackOverflowException:

services.TryAddEnumerable(ServiceDescriptor.Singleton<IHostedService, JobHostService>());

异常表现为调用栈因循环引用不断重复,最终导致栈溢出。

我的Startup类代码如下:

[assembly: WebJobsStartup(typeof(Startup))]
namespace FuncApp
{
public class Startup : IWebJobsStartup
{
    public void Configure(IWebJobsBuilder builder)
    {
        var config = new ConfigurationBuilder()
            .AddJsonFile("local.settings.json", optional: true, reloadOnChange: true)
            .AddEnvironmentVariables()
            .Build();

        builder.Services
            .AddSingleton<IConfiguration>(config)
            .AddSingleton(serviceProvider => serviceProvider)
            .AddLogging();
    }
}
}

注:该函数几周前运行正常,未修改代码的情况下突然无法运行。

复现步骤

  • 使用Visual Studio 2019或2022创建Azure触发器函数
  • 添加上述Startup类及代码
  • 运行程序,问题出现

问题原因及解决方法

问题出在AddSingleton(serviceProvider => serviceProvider)这一行:手动注册返回容器自身的IServiceProvider单例,会和Azure Functions内置的JobHostService形成循环依赖——JobHostService初始化时需要依赖IServiceProvider,而自定义注册的逻辑会导致容器解析时不断循环调用,最终触发栈溢出。

直接移除这一行代码即可解决问题:

builder.Services
    .AddSingleton<IConfiguration>(config)
    .AddLogging();

IServiceProvider是DI容器内置的核心服务,无需手动注册,自定义注册反而会破坏容器正常的解析逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 12:50:28