6

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;
        }
Dejna93
  • 31
  • 4
Shailendra
  • 153
  • 3
  • 11
  • `Azure Function` is a type of application similar to a REST API service, not a language feature. Very few (if any) of its classes are static. Given the *fact* that app instances are short-lived, even static classes will get recycled and lose any data they held after a few minutes – Panagiotis Kanavos Jan 20 '20 at 10:22
  • What is the *actual* problem? Why ask whether an Azure Function app can use static classes or not? – Panagiotis Kanavos Jan 20 '20 at 10:25
  • @PanagiotisKanavos I have edited the question details – Shailendra Jan 20 '20 at 12:16
  • Does this answer your question? [Azure functions - should functions be written inside static classes](https://stackoverflow.com/questions/45168659/azure-functions-should-functions-be-written-inside-static-classes) – Tim Abell Aug 06 '20 at 11:51

2 Answers2

13

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.

niaher
  • 9,460
  • 7
  • 67
  • 86
Ivan Glasenberg
  • 29,865
  • 2
  • 44
  • 60
0

This is not entirely true though - I just ran into some trouble with non static timer triggered functions. In my case I needed dependency injection in terms of entity framework, but this non static instance is now causing me trouble in order to call the admin endpoint to trigger the function when doing development locally.

See more on how to normally invoke static timer triggered functions here: What is the simplest way to run a timer-triggered Azure Function locally once?