Worker Services in .NET Core 3.0 - The New Way to Create Services

3 min read 8 hours ago
Published on Nov 22, 2024 This response is partially generated with the help of AI. It may contain inaccuracies.

Table of Contents

Introduction

In this tutorial, we will explore how to create a Worker Service using .NET Core 3.0. Worker Services are a powerful way to run background tasks and can be deployed as Windows Services or run as console applications. This guide will walk you through the creation, configuration, and deployment of a Worker Service, including logging with Serilog.

Step 1: Create the Demo Worker Service App

  1. Open your terminal or command prompt.
  2. Use the following command to create a new Worker Service project:
    dotnet new worker -n DemoWorkerService
    
  3. Navigate to the project directory:
    cd DemoWorkerService
    
  4. Open the project in your preferred IDE (e.g., Visual Studio, Visual Studio Code).

Step 2: Understand What a Worker Service Is

  • A Worker Service is a template designed for background processing applications.
  • It can run as a Windows Service, Linux service, or in a container.
  • The main function of a Worker Service is to perform long-running tasks in the background.

Step 3: Overview of Service App Template Code

  • Inspect the default code generated by the Worker Service template.
  • Focus on the Worker.cs file, which contains the core logic for your service.
  • Identify the ExecuteAsync method where the background processing logic will reside.

Step 4: Design Service App Code Using HttpClient

  1. Add the HttpClient service to your project for making web requests.
  2. In your Worker class, inject IHttpClientFactory to create an instance of HttpClient.
  3. Use the following code snippet to set up HttpClient in your Worker class:
    public class Worker : BackgroundService
    {
        private readonly IHttpClientFactory _httpClientFactory;
    
        public Worker(IHttpClientFactory httpClientFactory)
        {
            _httpClientFactory = httpClientFactory;
        }
    
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            // Your background logic here
        }
    }
    

Step 5: Implement Logging with Serilog

  1. Add the Serilog NuGet package to your project:
    dotnet add package Serilog.AspNetCore
    
  2. Configure Serilog in the Program.cs file:
    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .UseSerilog() // Add this line
            .ConfigureServices((hostContext, services) =>
            {
                services.AddHostedService<Worker>();
            });
    

Step 6: Configure Serilog

  • Set up Serilog configuration in the appsettings.json file:
    {
      "Serilog": {
        "Using": [],
        "MinimumLevel": "Information",
        "WriteTo": [
          { "Name": "Console" },
          { "Name": "File", "Args": { "path": "logs/myapp.txt" } }
        ]
      }
    }
    
  • Make sure to include the necessary namespaces for configuration.

Step 7: Configure Worker Service for Windows

  1. Add the Windows Services NuGet package:
    dotnet add package Microsoft.Extensions.Hosting.WindowsServices
    
  2. Modify the CreateHostBuilder method to support Windows Services:
    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .UseWindowsService() // Add this line
            .ConfigureServices((hostContext, services) =>
            {
                services.AddHostedService<Worker>();
            });
    

Step 8: Deploy the Service App

  • Publish your application for deployment:
    dotnet publish -c Release
    
  • Navigate to the published folder and find your executable.

Step 9: Install the Service Using PowerShell

  1. Open PowerShell as an Administrator.
  2. Use the following command to install the service:
    New-Service -Name "DemoWorkerService" -BinaryPathName "C:\path\to\your\executable.exe" -StartupType "Automatic"
    

Step 10: Uninstall the Service Using PowerShell

  1. To uninstall the service, use the command:
    Remove-Service -Name "DemoWorkerService"
    

Step 11: Update, Deploy, Install, and Uninstall the Service

  • For updating, ensure you publish the new version and repeat the installation process.
  • Use the same uninstall command to remove the old version before installing the new one.

Conclusion

You have now created and deployed a Worker Service using .NET Core 3.0. Key takeaways include understanding how to use HttpClient for background tasks, implementing logging with Serilog, and managing your service through PowerShell. Next steps involve exploring more complex functionalities and possibly integrating your Worker Service with other applications or services.