Azure functions - should functions be written inside static classes

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.


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();
    }
}