How to ensure only one instance of IHostedService is running within a .NET core 2.2 Web API
Asked Answered
O

1

3

I have a .NET Core 2.2 web API that can be scaled out to several instances based on demand. This API has a background service (IHostedService) that should only run on one of the instances at a time.

Is there a common approach or design pattern to ensure this service is only running on one instance at any given point in time?

Orv answered 26/9, 2019 at 12:22 Comment(0)
B
2

The ability to include a hosted service along with the actual application is just like anything else in Core. You can use all of MVC, API and Razor Pages, all in the same project if you want, for example. However, at a certain point, 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.

FWIW, if you can make the jump, ASP.NET Core 3.0 now has a worker service template that would fit the bill nicely. You don't have to upgrade to deploy the hosted service on its own, but it will make your life easier. You can also just go 3.0 for that one project; just because you're using 3.0 on one thing, doesn't mean every project has to be upgraded as well.

Broughton answered 26/9, 2019 at 12:59 Comment(4)
That's kind of what I figured, but I remember web jobs being able to to be configured as singletons where that framework handled ensuring only one instance of the web job was running at any point in time so I didn't know if I could possibly use the same pattern for my hosted service.blogs.msdn.microsoft.com/waws/2014/05/19/…Orv
Hosted services are singletons, but each instance of your app is a separate process with a separate singleton instance.Broughton
Understood, but did you see how the web job is implemented? Runs on all instances that the web app runs on. You can optionally restrict the WebJob to a single instance. learn.microsoft.com/en-us/azure/app-service/webjobs-createOrv
It's scheduled on the instance but it doesn't run in the same process as the web app. Hosted services do run in the same process. They are not the same thing.Broughton

© 2022 - 2024 — McMap. All rights reserved.