简体   繁体   English

Static 与 Azure 函数中的非静态类和方法

[英]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.几乎所有Azure Functions示例都使用 static class 和 ZA81259CEF84E959C294EDDF1 方法。

[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.但是,我至少看到了一个示例,其中触发器是使用非静态方法在非静态 class 中定义的。 See HttpTrigger2 here .请参阅此处HttpTrigger2

[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.到目前为止,我所有的函数都是 static,但我已经厌倦了这种代码模式,因为我经常不得不提取私有方法来提高可读性。 This forces me to pass multiple parameters to these methods so I avoid fetching the same data or instantiating the same object.这迫使我将多个参数传递给这些方法,因此我避免获取相同的数据或实例化相同的 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.理想情况下,我应该能够定义 class 变量并在任何地方使用它们。

My question is are we supposed to be declaring functions static since Functions is supposed to be serverless?我的问题是我们应该声明函数 static 因为Functions应该是无服务器的吗? How does the runtime behave in the case of the second example?在第二个示例的情况下,运行时的行为如何?

Functions could be static or not.函数可以是 static 或不是。 Using non-static class/method will allow you to use dependency injection for example.例如,使用非静态类/方法将允许您使用依赖注入。

There is an interesting related post here:这里有一个有趣的相关帖子:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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