Home > Net >  Static vs non-static classes and methods in Azure Functions
Static vs non-static classes and methods in Azure Functions

Time:08-17

Virtually every Azure Functions example out there is using a static class with static methods.

[FunctionName("HttpTriggerCSharp")]
public static async Task<IActionResult> Run(
    [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)]
    HttpRequest req, ILogger log);

However, I've seen at least one example where a trigger was defined in a non-static class with a non-static method. See HttpTrigger2 here.

[FunctionName("HttpTrigger2")]
public Task<IActionResult> Run(
    [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = null)]
    HttpRequest req, ExecutionContext context, ILogger log)

So far, all of my functions are static, but I'm getting sick of this code pattern because often I have to extract private methods to help with readability. This forces me to pass multiple parameters to these methods so I avoid fetching the same data or instantiating the same object. In the end, development slows down and I have long method signatures. Ideally, I should be able to define class variables and use them wherever.

My question is are we supposed to be declaring functions static since Functions is supposed to be serverless? How does the runtime behave in the case of the second example?

CodePudding user response:

Functions could be static or not. Using non-static class/method will allow you to use dependency injection for example.

There is an interesting related post here:

  • Related