Search code examples
.netwindows-services.net-8.0

Is it possible to use .NET 8 for a windows service?


I'm trying to create a new windows service in visual studio 2022 with the latest LTS release of .NET (8.0).

In visual studio when I go to create a windows service, it won't let me choose a modern version of .NET. The newest I can choose is V4.

What's the situation here, is this correct? Is it not possible to use .NET 8 in a windows service?

Kind regards,


Solution

  • It's possible and Visual Studio does have a template. The problem is cause because .NET 8 is actually a .NET Core version. .NET 5 and later are actually .NET Core versions with the Core part removing for marketing purposes.

    The template you need is the Worker Service template, available at least since .NET Core 3 (perhaps even 2). This creates a cross-platform background service that can be hosted on Linux or Windows by adding the proper NuGet package.

    The template itself creates Worker class derived from BackgroundService and starts it:

    The Program.cs contains just this

    using App.WorkerService;
    
    HostApplicationBuilder builder = Host.CreateApplicationBuilder(args);
    builder.Services.AddHostedService<Worker>();
    
    IHost host = builder.Build();
    host.Run();
    

    The initial worker class is

    namespace App.WorkerService;
    
    public sealed class Worker(ILogger<Worker> logger) : BackgroundService
    {
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            while (!stoppingToken.IsCancellationRequested)
            {
                logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);
                await Task.Delay(1_000, stoppingToken);
            }
        }
    }
    

    This project can run anywhere. Create Windows Service using BackgroundService shows the changes needed to host it as a service. The most important one is to install the Microsoft.Extensions.Hosting.WindowsServices and call AddWindowsService to register the service and allow it to be controlled using service commands.

    Services usually run using restricted accounts that can't just register services. An administrator can install the service using a Windows Installer package. Create a Windows Service installer shows how to create an installer for this case.

    Another option is to use sc create from the command line to register an executable as a Windows service.

    sc create TestService binpath= C:\Path\To\myservice.exe
    

    In PowerShell, the same thing can be done using the New-Service command

    New-Service -Name "TestService" -BinaryPathName 'C:\Path\To\myservice.exe'