Home > Software engineering >  Dependency Injection in Azure function
Dependency Injection in Azure function

Time:05-31

I have a time-triggered Azure function & I want to use a custom service inside it i.e all my code to be executed inside the run method is under that custom service & I am just calling that service from the run method using DI, so is it correct approach to do?

CodePudding user response:

By default, Azure Functions (C#) Timer Trigger uses the static Run methods where you do not have dependencies, and these are the functional methods strives to be pure.

public  static  void  Run([TimerTrigger("0 */5 * * * *")]TimerInfo myTimer, ILogger log)

To construct and use the DI in Run Method of Azure Functions Timer Trigger, try using the Non-Static Run method.

Few Steps of using the DI in Azure Functions Timer Trigger were:

  1. In Root Project Level > Startup class should register all the dependency classes used in the Azure Function app and also that Startup class needs to implement the FunctionsStartup.
  2. When you remove the static keyword then static class cannot have a constructor, so we have to use a kind of [Constructor Injection] and register the ILogger service to log the data.

Refer to the practical workarounds given in the AkshayBabannaavar Medium Blog, MarcRoussy Blog and SO Thread1 on Azure Functions (C#) Timer Trigger Dependency Injections for more information.

CodePudding user response:

This is an example of a TimerTrigger function I use in one of our projects, its a clean and scalable approach. As you see here I am injecting ILogger, OutboxRepository and ITimeProvider:

Function.cs

internal class ForwardEventLogMessages
    {
        private readonly ILogger _logger;
        private readonly OutboxRepository _outboxRepository;
        private readonly ITimeProvider _timeProvider;

        public ForwardEventLogMessages(
            ILoggerFactory loggerFactory,
            OutboxRepository outboxRepository,
            ITimeProvider timeProvider)
        {
            _logger = loggerFactory.CreateLogger<ForwardEventLogMessages>();
            _outboxRepository = outboxRepository;
            _timeProvider = timeProvider;
        }

        [Function(nameof(ForwardEventLogMessages))]
        public async Task Run([TimerTrigger("%MessagesSchedule%")] TimerInfo timerInfo)
        {
            _logger.LogInformation("Start forwarding event logs");

            await _outboxRepository.TransferFromLog(
                dateTime: _timeProvider.GetCurrentDateTime());
        }
    }

And make sure to register your services in the Program.cs/Startup.cs dependent on framework version, if you use isolated functions or in-proc, etc. You can read more about DI in Az functions here: https://docs.microsoft.com/en-us/azure/azure-functions/functions-dotnet-dependency-injection

  • Related