I'm starting to try out Azure functions. I'm using Visual Studio 2017 Preview version 15.3. When I right click on the Azure Functions project I created, and select Add>New Item...>Azure Function, the default template Visual Studio generates is of a public static class
with a public static async Task
method (the function).
Does the class need to be static (I changed it to non-static and it seems to work)? Is that a best practice for Azure functions? If that is the case, what problems might rise by using a non-static class to hold the Azure Function method?
but why it is declared as static by default? By default, whenever you create an Azure Function, it comes in a template with a static class and a static method. Microsoft enabled instance methods for Azure Functions, now we are able to have non-static classes and methods for our functions.
Durable Functions is an extension of Azure Functions. You can use Durable Functions for stateful orchestration of function execution. A durable function app is a solution that's made up of different Azure functions. Functions can play different roles in a durable function orchestration.
They are faster — Static methods are slightly faster than instance methods because in instance methods, you are also working with an implicit this parameter. Eliminating that parameter gives a slight performance boost in most programming languages.
As always it depends. Among other answers which stay to keep function class static, I would like to present another case where the non-static class can be helpful. Please look at: Functions dependency injection. If you want use DI inside your functions there is no easy way to do it with static class because it's can not have instance constructors with parameters. So you are not able to write something like this:
public class HttpTrigger
{
private readonly IMyService _service;
private readonly HttpClient _client;
public HttpTrigger(IMyService service, IHttpClientFactory httpClientFactory)
{
_service = service;
_client = httpClientFactory.CreateClient();
}
[FunctionName("GetPosts")]
public async Task<IActionResult> Get(
[HttpTrigger(AuthorizationLevel.Function, "get", Route = "posts")] HttpRequest req,
ILogger log)
{
log.LogInformation("C# HTTP trigger function processed a request.");
var res = await _client.GetAsync("https://microsoft.com");
await _service.AddResponse(res);
return new OkResult();
}
}
Given that the functions are invoked in a serverless fashion, static methods have the correct semantics here, i.e., you should assume the process can exit after every function invocation, and so you shouldn't be accumulating state on instance methods in between function invocations.
That said, we are investigating Dependency Injection.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With