Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET Core Difference between Hosted Service and Singleton Service

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.

like image 700
Azaz ul Haq Avatar asked Apr 22 '19 15:04

Azaz ul Haq


People also ask

What is hosted service in .NET Core?

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.

What is singleton service in .NET Core?

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.

What is the difference between transient and singleton?

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.

What is scoped service in .NET Core?

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.


1 Answers

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.

like image 94
poke Avatar answered Oct 12 '22 00:10

poke