Home > Enterprise >  What is the ServiceLifetime of IServiceProvider in a Time Trigger Azure Functions
What is the ServiceLifetime of IServiceProvider in a Time Trigger Azure Functions

Time:12-31

I am observing that the hashCode of _serviceProvider is the same throughout all the execution of the below function at an interval of 1 min.

using Microsoft.Azure.WebJobs;
using Microsoft.Extensions.Logging;
using System;

namespace TestFunction
{
    public class Function2
    {
        private readonly IServiceProvider _serviceProvider;
        public Function2(IServiceProvider serviceProvider)
        {
            _serviceProvider = serviceProvider;
        }

        [FunctionName("Function2")]
        public void Run([TimerTrigger("0 */1 * * * *")] TimerInfo myTimer, ILogger log)
        {
            var hashCode = _serviceProvider.GetHashCode();
            log.LogInformation($"C# Timer trigger function executed at: {DateTime.Now}");
        }
    }
}

Version:

<TargetFramework>netcoreapp3.1</TargetFramework>
<AzureFunctionsVersion>v3</AzureFunctionsVersion>
<PackageReference Include="Microsoft.NET.Sdk.Functions" Version="3.0.13" />

FYI: I also compared the hashcode of serviceProvider in an API for two requests at the same endpoint but they are different.

Question: What is the lifetime of IServiceProvider in a Time Trigger Azure Functions?

CodePudding user response:

Thank you @akash, For the update.

Based on this MS DOC:

For a Functions app, the different service lifetimes behave as follows:

Transient: Transient services are created upon each resolution of the service.

Scoped: The scoped service lifetime matches a function execution lifetime. Scoped services are created once per function execution. Later requests for that service during the execution reuse the existing service instance.

Singleton: The singleton service lifetime matches the host lifetime and is reused across function executions on that instance. Singleton lifetime services are recommended for connections and clients, for example DocumentClient or HttpClient instances.

View or download a sample of different service lifetimes on GitHub.

For more information please refer the below links:

SO THREAD : Azure Function V3 Dependency Injection Lifetime

BLOG: Dependency Injection in Azure Functions

CodePudding user response:

IServiceProvider is just an interface for the service collection. But it's implemented by e.g. HttpContext used in ASP.NET. HttpContext has a lifetime of a request, i.e. it is Scoped.

  • Related