如何确保IHostedService的仅一个实例在.NET Core 2.2 Web API中运行 [英] How to ensure only one instance of IHostedService is running within a .NET core 2.2 Web API

查看:45
本文介绍了如何确保IHostedService的仅一个实例在.NET Core 2.2 Web API中运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个.NET Core 2.2 Web API,可以根据需求扩展到多个实例.此API具有后台服务(IHostedService),该服务一次只能在一个实例上运行.

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?

推荐答案

将托管服务与实际应用程序包括在一起的功能与Core中的其他功能一样.例如,您可以在同一项目中使用所有的MVC,API和Razor页面.但是,在某些时候,最好将它们分解为单独的应用程序,在这种情况下也是如此.如果只希望托管服务的一个实例,则应将其分解为一个单独的项目,然后部署该实例的一个实例.如果在应用程序内部部署它,则每个应用程序实例都有一个实例.没办法解决.

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,如果可以进行改进,那么ASP.NET Core 3.0现在具有一个工作人员服务模板,可以很好地满足您的要求.您无需升级即可自行部署托管服务,但这将使您的生活更轻松.您也可以为该项目使用3.0.仅仅因为您在一件事上使用3.0,并不意味着每个项目也都必须升级.

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.

这篇关于如何确保IHostedService的仅一个实例在.NET Core 2.2 Web API中运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆