How to use IHostedService in ASP.Net Core

Source: InfoWorld

Take advantage of the IHostedService interface to execute background tasks in your ASP.Net Core applications

We often need to execute background tasks and scheduled jobs in our applications. To implement background tasks in ASP.Net Core, you can take advantage of Azure WebJobs or any of a number of third-party task schedulers like Quartz or Hangfire.

In ASP.Net Core, you can implement background tasks as hosted services as well. A hosted service is a class that implements the IHostedService interface and includes the necessary code for running tasks in the background. This article presents a discussion of how we can build hosted services in ASP.Net Core.

At the time of this writing, Visual Studio 2019 is available for free download. If you don’t already have a copy of Visual Studio 2019 installed in your system, you can download it from Microsoft’s Visual Studio downloads page

Create an ASP.Net Core project in Visual Studio

First off, let’s create an ASP.Net Core project in Visual Studio. To do that, follow the steps given below to create a new ASP.Net Core project in Visual Studio 2019.

  1. Launch the Visual Studio IDE.
  2. Click on “Create new project.”
  3. In the “Create new project” window, select “ASP.Net Core Web Application” from the list of the templates displayed.
  4. Click Next. 
  5. In the “Configure your new project” window, specify the name and location for the new project.
  6. Click Create.
  7. In the “Create New ASP.Net Core Web Application” window, select .Net Core as the runtime and ASP.Net Core 2.2 (or later) from the drop-down list at the top.
  8. Select “Web Application” as the project template.
  9. Ensure that the check boxes “Enable Docker Support” and “Configure for HTTPS” are unchecked as we won’t be using those features here.
  10. Ensure that Authentication is set as “No Authentication” as we won’t be using authentication either.
  11. Click to create.

Pentechs've been excellent and a pleasure to work with.  Despite the complexity of the project they've delivered a superb result and kept all their promises.

CEO, Digiclips, UK

See what our clients say

Want to start a project?

Contact us at

+91 886 110 9173

+91 997 289 6003

+91 80 4200 7229