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.
In ASP.NET Core, background tasks can be implemented as hosted services. A hosted service is a class with background task logic that implements the IHostedService interface. This article provides three hosted service examples: Background task that runs on a timer.
Singleton is a design pattern, It means that there will be a single copy of your object inside server memory, which will be shared among all the requests (http/client). So, when you register any dependency in your application as a Singleton, then you will get a single copy of an object per server/node/instance.
Singleton is a single instance for the lifetime of the application domain. Scoped is a single instance for the duration of the scoped request, which means per HTTP request in ASP.NET. Transient is a single instance per code request.
In Asp.Net Core a new service scope will be created at each request and will be disposed when request ended with a response or an exception. A scoped service is requested; Service scope will create an instance of the service that has not been already created in the service scope.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With