Practical Implementation — .NET Core Background Services

ParTech
ParTech
Apr 19 · 6 min read

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.

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

Choose the type of web application as API.

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

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.

Inherit the IHostedService interface from Microsoft.Extensions.Hosting.

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.

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.

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.

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

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

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

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.

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

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”*

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>();

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.

Originally published at https://www.partech.nl.

Nerd For Tech

From Confusion to Clarification

Nerd For Tech

NFT is an Educational Media House. Our mission is to bring the invaluable knowledge and experiences of experts from all over the world to the novice. To stay up to date on other topics, follow us on LinkedIn. https://www.linkedin.com/company/nerdfortech

ParTech

Written by

ParTech

We are the technical partner for your online platform and the best employer for web development professionals. Want to know more about ParTech? Partech.nl/nl

Nerd For Tech

NFT is an Educational Media House. Our mission is to bring the invaluable knowledge and experiences of experts from all over the world to the novice. To stay up to date on other topics, follow us on LinkedIn. https://www.linkedin.com/company/nerdfortech

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store