问题
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?
回答1:
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.
来源:https://stackoverflow.com/questions/58116722/how-to-ensure-only-one-instance-of-ihostedservice-is-running-within-a-net-core