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

Azure Functions中Program.cs未启动,依赖注入失败问题排查

问题描述

我有一个Azure Functions函数,希望在Program.cs中注入自定义类,但发现Program.cs并未启动,设置的断点未触发,同时出现服务未注入的错误。

我的Program.cs代码:

var host = new HostBuilder()
.ConfigureAppConfiguration((hostContext, configBuilder) =>
{
    configBuilder.AddJsonFile("local.settings.json", true, true);
})
.ConfigureFunctionsWorkerDefaults()
.ConfigureLogging(loggingBuilder =>
{
    loggingBuilder.AddConsole();
})
.ConfigureServices((hostContext, services) =>
{
    var connectionString = hostContext.Configuration.GetConnectionString("incontrol");

    services.AddDbContext<DataContext>(options => { options.UseSqlServer(connectionString); });

})
.Build();

host.Run();

我的functions.csproj配置:

<PropertyGroup>     
    <TargetFramework>net8.0</TargetFramework>
    <AzureFunctionsVersion>v4</AzureFunctionsVersion>
    <OutputType>Exe</OutputType>    
</PropertyGroup>

请问我遗漏了什么配置?


解决方案

问题根源在于Azure Functions隔离模式的启动标识缺失,按以下步骤修正:

  1. 添加隔离模式运行时配置
    在functions.csproj的<PropertyGroup>节点中加入<FunctionsWorkerRuntime>dotnet-isolated</FunctionsWorkerRuntime>,这是让运行时识别Program.cs作为启动入口的核心配置。修改后的配置如下:

    <PropertyGroup>     
        <TargetFramework>net8.0</TargetFramework>
        <AzureFunctionsVersion>v4</AzureFunctionsVersion>
        <OutputType>Exe</OutputType>
        <FunctionsWorkerRuntime>dotnet-isolated</FunctionsWorkerRuntime>    
    </PropertyGroup>
    
  2. 确认必备NuGet包已安装
    确保项目已安装隔离模式的核心依赖包:

    • Microsoft.Azure.Functions.Worker
    • Microsoft.Azure.Functions.Worker.Sdk
      若使用EF Core,需保证Microsoft.EntityFrameworkCore.SqlServer等包版本与.NET 8兼容。
  3. 检查local.settings.json的输出配置
    右键local.settings.json文件,将“复制到输出目录”属性设置为“如果较新则复制”,确保程序启动时能读取到文件中的连接字符串配置。

  4. 调试环境验证
    本地调试时,确保启动项目为当前Functions项目,调试器附加的进程为dotnet.exe(隔离模式下不再是func.exe)。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 03:25:06