Does webjob SDK TimerTrigger support Dependancy injection?

AM Dev-Test 21 Reputation points
2022-12-06T05:29:23.597+00:00

I am using .net core 6 WebJob SDK Version 4.0.1:

<PackageReference Include="Microsoft.Azure.WebJobs.Extensions" Version="4.0.1" />

I added the following line to my webjob setup code:

builder.ConfigureServices(s => s.AddSingleton<MyClass>());

I have a timer trigger like this:

public class TimerFunctions  
{  
    public void TimerTriggerTest([TimerTrigger("*/5 * * * * *")] TimerInfo myTimer,   
        ILogger logger,  
        MyClass diTest  
          
        )  
    {  
        logger.LogInformation("TimerTrigger");  
    }  
}  

When run my WebJob project locally, I get the following error:

System.InvalidOperationException: Cannot bind parameter 'diTest' to type MyClass. Make sure the parameter Type is supported by the binding. If you're using binding extensions (e.g. Azure Storage, ServiceBus, Timers, etc.) make sure you've called the registration method for the extension(s) in your startup code (e.g. builder.AddAzureStorage(), builder.AddServiceBus(), builder.AddTimers(), etc.).  

How can I have Dependency Injection in my Azure Webjob code above?

Azure App Service
Azure App Service
Azure App Service is a service used to create and deploy scalable, mission-critical web apps.
8,965 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Ryan Hill 30,281 Reputation points Microsoft Employee Moderator
    2022-12-07T04:40:43.123+00:00

    It does, but the way you're doing it isn't the proper way. You're trying to inject the service in a method. The runtime (SDK) finding your timer trigger isn't going to pass the service because it isn't aware of it. The service needs to be injected in the constructor of your TimerFunctions class.

        public class Functions  
        {  
            private readonly IMyClass diTest;  
      
            public Functions(IMyClass diTest)  
            {  
                this.diTest = diTest;  
            }  
              
            public void ProcesTimerTrigger([TimerTrigger("*/5 * * * *")] TimerInfo timer, ILogger logger)  
            {  
                diTest.WorkIt();  
                logger.LogInformation("Timer elapsed...");  
            }  
              
            public void ProcessQueueMessage([QueueTrigger("queue")] string message, ILogger log)  
            {  
                diTest.WorkIt();  
                log.LogInformation(message);  
            }  
        }  
    

    Also, you don't need to use a TimerTrigger. You can configure your web job as a triggered job at your desired interval.

    0 comments No comments

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.