Practical Implementation: .NET Core BackgroundServices

16 april 2021 om 10:00 by ParTech Media - Post a comment

The advantage that computers and automation bring to our life is plenty. Handling tasks without human intervention and monitoring is definitely a boon for most people.

Here is a hypothetical scenario. You have a system that offers services over the cloud. The system is paid but offers a free trial period of 30 days. To validate the trial users and restricting their access after 30 days, you require constant monitoring. Also, if it's done manually then there is a possibility of errors such as ending the trial period earlier or providing an extended usage of the trial software.

This might create a negative impression about your product on the customer’s mind. To avoid this situation, you can make use of the power of computing that takes complete care of revoking the access at the right time.

To achieve this, .Net core provides the option of background services. In this, the logic is written in the .Net code and it can then be run in the background continuously. It provides the advantage of getting the requirement done without any human intervention. Let's see in detail what is background service and how it can be implemented in Dot Net Core

Table of contents

  1. Introduction to IHostedService
  2. Practical Implementation of .Net Hosted\background services
  3. Conclusion

Introduction to IHostedService

.Net core provides the option of implementing background jobs by using the IHostedServices. This comes as a part of .Net core libraries. HostedServices is the class that implements the IHostedService interface.

Hosted services are slightly different from Windows services, which are hosted separately and does not host any website along with it. But, when it comes to background services, it can be bound and made to run along with the website project.

Practical Implementation of Dot Net Core Hosted/Background services

In this section, let's see how to implement the background services. This will be done in two ways; first, using the IHostedServices and second, using the BackgroundService.

Step 1

Create a new project, and choose the project template as ‘ASP.NET Core Web Application’ and provide a valid name for the project.

Step 2

Choose the type of web application as API.

Step 3

Once the project is created, the folder structure of the project looks like below -

Step 4

The next step is to implement a class that consumes the IHostedService interface. Let's create a new class file and name it as per your choice.

Step 5

Inherit the IHostedService interface from Microsoft.Extensions.Hosting.

Step 6

IHostedService interface has two methods that require it to be implemented by the class that inherits it. One is the StartAsync and another is the StopAsync.

Step 7

Now in the Class that implements the IHostedService, let's create a timer globally and initialize the timer. We will do this by providing -

  • A method which we need to execute
  • The frequency or the time frame in which the method has to be executed.

Step 8

Inside the method name, insert the logic that needs to be run in the background. In our example, we have implemented a simple Console.WriteLine, a statement with the time and message to notify the interval at which the method is getting fired.

Step 9

In the startup.cs file, under the configure services section, add the below line to inject the hosted services into the application.

services.AddHostedService<PartechHostedService>();

Here, ‘PartechHostedService’ is the class name that has consumed IHostedService

Step 10

Header - using Microsoft.AspNetCore.Hosting needs to be added in PartechHostedServices and Startup class for consuming the IHostedService

Step 11

Change the project run settings to the name of the project from the dropdown and then run the project.

Step 12

Notice the result from the Console window. You will see that the application has started and endpoint data is available in the browser. You will also notice that the method intended to run in parallel is also providing the data in the Console window.

Thus, the process of achieving the background task along with the web application is achieved using the IHostedService interface and the method implementation.

Here, we have provided a timer variable and initialized it in the StartAsync method. This also holds the method that needs to be fired in a particular interval. And the method StopAsync gets fired just before the application gets stopped.

Let's see the other way of achieving the same functionality using the background services class instead of the IHostedService. In this method, the new class that is being created inherits the BackgroundService and it overrides the ExecuteAsync method.

The advantage of background services over hosted service is that it is an abstract class that implements the IHostedService interface. By default, it takes care of the Start and Stop Async elements that need to be implemented for the IHostedService.

In the upcoming steps, let's see how to implement the background services in the same project.

Step 13

Let's create a new class and inherit the background service and provide a valid header references for it.

Step 14

Create the override method ExecuteAsync method, with the necessary function that needs to be achieved. Here, we are going to print *DateTime.Now.ToString() + " Welcome to PARTECH World! From Background service"*

Step 15

In the startup.cs file, comment on the code that is being implemented for the IHostedService and create the new dependency injection for the new class by adding the below line in the Configureservices method of a startup.

services.AddTransient<IHostedService, PartechBackgroundService>();

Step 16

Now run the solution and observe the result. With the new code, the new message gets printed in the console window and runs as per the mentioned frequency.

Conclusion

With the help of IHosted and Background services, you can run background tasks with ease. The best part is you don’t need any infrastructure support. This approach will come in handy for short-running and simple tasks that need to be carried out at regular intervals.

Nieuwste