Reputation: 905
Why Azure function class is static by default?
public static async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Function, "get")] HttpRequest req,
ILogger log)
Is it because, Azure function based out of serverless architecture, using static or single class instance should result in saving compute resources? or 'static' decision is made for any other technical reasons?
I know Azure function class can be non-static as well from 2019 onwards but here my question is different what is Microsoft's technical decision behind, declaring the Azure function class as static by default. Knowing this reason or justification would be helpful in my software designing as well. Curious.
Again re-iterating my question as some of the folks answering Azure function class can also be non-static. My question is NOT whether Azure function class can be non-static? but why it is declared as static by default?
Upvotes: 3
Views: 2098
Reputation: 824
You got it. Exactly right with your first assumption.
Don't change your classes from being static. They are sealed by default. And it improves startup performance. It is not just because of how azure functions were originally designed.
public static class Program {
public static IHost? host;
public static async Task Main(string[] args) {
host = BuildFactory();
}
}
then you can call
Program.host.Services.GetService<IInterface>();
to get your singleton from the factory
you should only be putting in configurations and anything with lifetimes that need cleaned up and allocated dynamically. Sql connections, http pools, etc.
Do not put everything you want injected all over the place. Otherwise, a new factories should be created for every responsibility/purpose. And .NET isn't setup to easily allow for that.
Upvotes: 0
Reputation: 102
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.
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.
Knowing this reason or justification would be helpful in my software designing as well.
My concern was that if I have a static class, then all its members must be static. And then such a static variable would be shared across different requests to the function (or functions). So I would be effectively sharing state, while according to this learn.microsoft.com/en-us/azure/azure-functions/…, functions should be written to be stateless.
Upvotes: 1