25

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.

1
  • the docs state: When you register implementations of IHostedService using any of the AddHostedService extension methods - the service is registered as a singleton.
    – Menahem
    Commented May 2, 2023 at 11:56

1 Answer 1

41

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.

2
  • Is there any con to using the hosted service over a singleton? Say if I want my Singleton/HostedService to "check in" with other servers in the cluster on a regular ~10 minute interval, I would want to do this in a HostedService that is always running during the lifetime of the application right? What performance impact does that/could that have on the rest of the application?
    – whendon
    Commented May 27, 2022 at 21:09
  • 2
    @whendon Since a singleton service doesn’t do anything on its own unless you explicitly make it do something: Yes, a hosted service is what you want to use since the framework will activate it at the start of your application. In your case, you could inherit from BackgroundService and just have a loop using await Task.Delay(TimeSpan.FromMinutes(10)) to pause in between. It being async means that there will be mostly no impact on your performance during the wait time.
    – poke
    Commented May 29, 2022 at 11:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.