简体   繁体   中英

Does webjob SDK TimerTrigger support Dependency Injection?

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.).

Yes, the TimerTrigger in the Azure WebJobs SDK does support Dependency Injection (DI). You can use DI to inject dependencies into your timer trigger function by using the [Inject] attribute.

For example, you could use DI to inject a service or repository into your timer trigger function, like this:

public class MyTimerTrigger
{
    private readonly IMyService _myService;

    public MyTimerTrigger(IMyService myService)
    {
        _myService = myService;
    }

    [FunctionName("MyTimerTrigger")]
    public async Task Run([TimerTrigger("0 */5 * * * *")] TimerInfo timer)
    {
        // Use the injected service here
        await _myService.DoWorkAsync();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM