azureazure-functionsstatic-classesazure-function-app

Can I create non static Azure function class in C#, what are the consequences?


This non static class is required for constructor injection in Azure function and collection of custom telemetry events.

If we create an azure function app in visual studio, it creates default with static keyword like this:

public static async Task<IActionResult> Run(
                [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
                ILogger log)
{
     telemetryClient.TrackEvent(new Exception("Function started"));
}

But to use constructor dependency injection (for Temeltry client, i am using it), we need to remove static keyword.

public Function1(TelemetryClient telemetryClient)
        {
            _telemetryClient = telemetryClient;
        }

Solution

  • Previously, Azure Functions only supported static classes/methods. This restriction made DI via constructor impossible. However later the support for non-static classes/methods was implemented (see Support Instance Functions).

    So if you need to use DI via constructor, just change it to non-static. There are no consequences.