Reputation: 1747
From .NET Core 2.1 onward, we can now run background tasks with hosted service.
I believe we could achieve same by adding a Service Class to service container with Singleton scope.
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.
Upvotes: 27
Views: 12713
Reputation: 387507
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. This allows you to include start or shutdown behavior, e.g. 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.
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.
Upvotes: 41