简体   繁体   中英

Static vs non-static classes and methods in Azure Functions

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?

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:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM