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

北城以北 提交于 2021-01-28 21:02:36

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!