启动时的 Azure Function 运行 代码

Azure Function run code on startup

我正在尝试找到一种方法在我的 Azure 函数启动时 运行 一些代码(我在其中设置连接字符串、DI 和其他配置)。所以现在,它在生成的 function.json:

中调用 运行 方法作为入口点
"entryPoint": "MyFunctionApp.MessageReceiver.Run"

此 运行 方法使用 EventHubTrigger 并像这样处理传入消息:

[FunctionName("MessageReceiver")]
        public static void Run([EventHubTrigger("eventHubName", Connection = "eventHubConnection")]string message, TraceWriter log)
        {
            if (string.IsNullOrWhiteSpace(message))
            {
                log.Info($"C# Event Hub trigger function processed a message: {message}");
            }
        }

有没有一种方法可以在调用此 运行 方法之前在初始启动时 运行 一些代码?或者有没有办法声明我可以在此 class 之前调用的入口点,然后调用 运行() 并以某种方式传入触发器?我正在尝试找到一种方法来避免一些骇人听闻的事情,例如设置布尔属性以查看应用程序是否已启动。

您可以实现 IExtensionConfigProvider。这些将在 "Startup".

上扫描并执行
using Microsoft.Azure.WebJobs.Host.Config;
namespace MyFunctionApp
{
  public class Startup : IExtensionConfigProvider
  {
     public void Initialize(ExtensionConfigContext context)
     {
        // Put your intialization code here.
     }
  }
}

在 2019 Build 大会上,Microsoft 发布了在 Azure Function 应用程序启动时具有可调用方法的功能。这可用于注册 DI 类、创建静态数据库连接等

可以在 Azure Function Dependency Injection

找到这些新功能的文档