15
votes

I am trying to find a way to run some code one time (where I set connection strings, DI, and other configs) when my Azure function starts. So right now, it calls a Run method as the entrypoint with this in the generated function.json:

"entryPoint": "MyFunctionApp.MessageReceiver.Run"

This Run method uses an EventHubTrigger and processes incoming messages like so:

[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}");
            }
        }

Is there a way that I can run some code on the initial startup before this Run method is called? Or is there a way to declare an entrypoint that I can call before this class and then call Run() and somehow pass in the trigger? I am trying to find a way that avoids hackish stuff like setting boolean properties to see if the app has started.

2

2 Answers

14
votes

You can implement an IExtensionConfigProvider. Those will be scanned and execute on "Startup".

using Microsoft.Azure.WebJobs.Host.Config;
namespace MyFunctionApp
{
  public class Startup : IExtensionConfigProvider
  {
     public void Initialize(ExtensionConfigContext context)
     {
        // Put your intialization code here.
     }
  }
}
9
votes

At the 2019 Build conference, Microsoft released the functionality to have a callable method when the Azure Function app starts up. This can be used for registering DI classes, creating static DB connections, etc.

The documentation for these new features can be found at Azure Function Dependency Injection