Lifetime of object created to call non-static Azure Function

Buck I 36 Reputation points
2021-04-27T17:43:14.453+00:00

I'm writing Azure Functions where the functions are non-static methods (in non-static classes, of course), so that I can use dependency injection. One thing I'm not clear on is the lifetime of the object that the methods are called on. Is it guaranteed that the framework creates a new object of your class each time one of the functions is triggered, or are objects re-used?

Specifically, if a new object is created each time it means that 1) dependencies are resolved each time; 2) the object is always a "fresh" newly-constructed one when your function is called; and 3) it is safe to store things in the object that only pertain to the that invocation of your Azure Function. Are those things true?

Azure Functions
Azure Functions
An Azure service that provides an event-driven serverless compute platform.
5,929 questions
0 comments No comments
{count} vote

1 answer

Sort by: Most helpful
  1. MikeUrnun 9,777 Reputation points Moderator
    2021-05-10T05:53:21.663+00:00

    Hi @Buck I

    You may have already read & reviewed in the doc but the lifetimes of dependency services are inherently the same ones defined in the ASP.NET Dependency injection: Transient - instance per constructor injection, Scoped - instance per execution (function invocation), and Singleton - per process, which are called as follows:

    builder.Services.AddTransient<IOperationTransient, Operation>();  
    builder.Services.AddScoped<IOperationScoped, Operation>();  
    builder.Services.AddSingleton<IOperationSingleton, Operation>();  
    

    You would then need to choose the lifetime that is the best fit for the particular service that's being registered in your Startup.cs file and how would use it later on in your function.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.