Search code examples
asp.net-coreazure-web-app-serviceautoscalingasp.net-core-hosted-services

Run IHostedService on only one instance of a scaled out Azure App Service


Is it possible to run an IHostedService on only one instance of a scaled out Azure App Service in ASP.NET Core? Or would the solution be to run this IHostedService in its own app service with one instance?

I have a BackgroundService that runs once a day and sends out reports via email. This service will run twice a day at the same time when my App Service is scaled out to 2 instances, resulting in two identical emails being sent.

How can I solve this problem?


Solution

  • It's better to break out things into separate apps, and that's the case here as well. If you only want one instance of your hosted service, you should break it out into a separate project and deploy one instance of that. If you deploy it inside your app, there will be an instance per instance of your app; there's no way around that, refer to this thread.

    With Hosted Services, there is an instance running of that hosted service for every deployment of your website which can be an issue if you only want one instance of that “process” running at anytime. You can program around this by creating your own locking mechanism, but obviously webjobs gets this out of the box. So you can use webjob running as a singleton to achieve what you want. Refer to the article about Hosted Services In ASP.NET Core.