简体   繁体   English

托管服务和Singleton服务之间的.NET核心差异

[英].NET Core Difference between Hosted Service and Singleton Service

From .NET Core 2.1 onward, we can now run background tasks with hosted service . 从.NET Core 2.1开始,我们现在可以使用托管服务运行后台任务。

I believe we could achieve same by adding a Service Class to service container with Singleton scope. 我相信我们可以通过向具有Singleton范围的服务容器添加服务类来实现相同目的。

What are the benefits of having a hosted service over a service with singleton scope? 通过具有单一范围的服务提供托管服务有什么好处? What are the key differences? 有哪些主要区别?

We can inject singleton scoped service to a controller and manipulate it with every new request. 我们可以将单一作用域服务注入控制器并对每个新请求进行操作。 However, this is not possible for hosted services. 但是,托管服务无法做到这一点。

A hosted service is effectively a singleton service. 托管服务实际上是单例服务。 The difference is that a hosted service has a specific lifetime: When the (web) host starts, the hosted service is started, and when the (web) host shuts down, the hosted service is also explicitly terminated. 不同之处在于托管服务具有特定的生命周期:当(Web)主机启动时,托管服务启动,当(Web)主机关闭时,托管服务也会明确终止。 This allows you to include start or shutdown behavior, eg to establish or terminate a connection to an external service. 这允许您包括启动或关闭行为,例如,建立或终止与外部服务的连接。

In contrast, normal services registered as singleton are only instantiated when they are first resolved and disposed when the service provider gets disposed during application shutdown. 相反,注册为singleton的普通服务仅在首次解析时进行实例化,并在服务提供者在应用程序关闭期间处置时进行处理。

As such, hosted services give you a lot more control about what to do with a service when an application starts or stops. 因此,当应用程序启动或停止时,托管服务可以让您更好地控制如何处理服务。 But there's isn't a lot magic involved with this. 但是这并没有太大的魔力。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM