Is it possible to run a custom IHostedService before the main function host starts?

Justin 1 Reputation point
2022-07-20T06:19:12.037+00:00

Hi MS,

I was hoping to run a custom IHostedService before the main Functions Host starts.

Is this possible?

For example -> I have a few queue triggers. They work 100% great. I was hoping to run my custom IHostedService which creates those queues if they don't exist already. Once that custom host finishes, then the main/normal Host will start/run.

I thought this might be the way, but wasn't sure if this is the recommendation:

   program.cs  
     
   var host = new HostBuilder()  
       .ConfigureFunctionsWorkerDefaults()  
     
       .ConfigureServices((appBuilder, services) =>  
       {  
           // Create an initialization service, which SHOULD run before the main function service.  
           services.AddSingleton<IHostedService, InitializationService>();  
       }  
       .Build();  
     
   host.Run();  
     
     
     
   InitializationService.cs  
     
   public class InitializationService : IHostedService  
   {  
       private readonly string _azureStorageConnectionString;  
       private readonly ILogger<InitializationService> _logger;  
     
       public InitializationService(IOptions<ConnectionStringOptions> connectionStringOptions, ILogger<InitializationService> logger)  
       {  
           _azureStorageConnectionString = connectionStringOptions.Value.AzureStorage;  
           _logger = logger;  
       }  
     
       public async Task StartAsync(CancellationToken cancellationToken)  
       {  
           // My logic in here, like creating an azure storage QueueClient and then creating the queue(s) if they don't exist.  
       }  
     
       public Task StopAsync(CancellationToken cancellationToken)  
       {  
           return Task.CompletedTask;  
       }  
   }  

Can anyone help?

Azure Functions
Azure Functions
An Azure service that provides an event-driven serverless compute platform.
4,448 questions
{count} votes

1 answer

Sort by: Most helpful
  1. MughundhanRaveendran-MSFT 12,446 Reputation points
    2022-07-22T09:52:38.167+00:00

    Hi @Justin ,

    Since Azure functions support .net core and .net 6, you can register services in the startup.cs like you have implemented. However it is receommended to start the function host first and then start the other services. If this is your requirement, you can test it locally and deploy to Azure to check if it is working as expected.

    Please let me know if you have any queries or concerns.

    0 comments No comments