1

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?

user246392
  • 2,661
  • 11
  • 54
  • 96
  • 1
    function could be static or not. using non static class and method will allow you to use dependency injection if needed. – Thomas Aug 14 '22 at 04:41
  • 1
    @Thomas why dont you post this as answer ? :) – Vova Bilyachat Aug 16 '22 at 01:05
  • >how does the runtime behave in the case of the second example? By design principles, Azure Functions should be in stateless to maintains its serverless functionality! If static class is declared, you will achieve stateless nature in instance methods! –  Aug 16 '22 at 01:06
  • Agree to Thomas comment, please check this [SO Thread](https://stackoverflow.com/q/45168659) where you'll get more information about using static and non-static classes in Azure functions and runtime behavior. –  Aug 16 '22 at 01:07

1 Answers1

3

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:

Thomas
  • 24,234
  • 6
  • 81
  • 125