Passaggio all'ora legale 30 marzo 2025 02:00 03:00 sposta avanti l'orologio di 1 ora (si dorme 1 ora in meno)
Un servizio windows può essere creato partendo dal template Worker Service di Visual Studio 2019

Creazione progetto

Il progetto può essere creato da interfaccia grafica di Visual Studio 2019 o da linea di comando

DOS / Batch file

dotnet new worker -o Sgart.Net5.WorkerService
Per renderlo a tutti gli effetti un servizio windows, va installato il pacchetto NuGet Microsoft.Extensions.Hosting.WindowsServices

DOS / Batch file

dotnet add package Microsoft.Extensions.Hosting.WindowsServices
e aggiunto .UseWindowsService() in CreateHostBuilder

C#: Programm.cs

namespace Sgart.Net5.WorkerService
{
    public class Program
    {
        public static void Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run();
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureServices((hostContext, services) =>
                {
                    // registro il Worker
                    services.AddHostedService<Worker>();
                })
                .UseWindowsService(); // lo configuro come Windows Service
    }
}
il Worker Service di esempio è questo

C#: Worker.cs

namespace Sgart.Net5.WorkerService
{
    public class Worker : BackgroundService
    {
        private readonly ILogger<Worker> _logger;

        public Worker(ILogger<Worker> logger)
        {
            _logger = logger;
        }

        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            while (!stoppingToken.IsCancellationRequested)
            {
                _logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);
                await Task.Delay(1000, stoppingToken);
            }
        }
    }
}
Questo è tutto, può essere eseguito in debug premendo F5 senza necessità di installarlo.

Installazione

Per installarlo come servizio windows si può usare il comando DOS sc.exe, ad esempio

DOS / Batch file: sc create

sc create "SgartNet5WorkerService" DisplayName="Sgart Demo Service" binPath="C:\...\Sgart.Net5.WorkerService.exe"

sc description SgartNet5WorkerService "Sgart.it servizio demo in .NET 5"
Eseguire i comandi con elevati privilegi.
può essere avviato o fermato con

DOS / Batch file: sc start/stop

sc start "SgartNet5WorkerService"

sc stop "SgartNet5WorkerService"
Il nome SgartNet5WorkerService è arbitrario, si può scegliere qualsiasi nome, l'unico vincolo è che non sia in conflitto con un servizio esistente.
Il servizio viene installato con l'utente NT AUTHORITY\SYSTEM.
Se deve accedere a risorse esterne come database o file system, sarà necessario riconfiguralo per girare con un utente di dominio.
Quando non serve più, può essere rimosso con

DOS / Batch file: sc delete

sc delete "SgartNet5WorkerService"

Per verificare se l'installazione è andata a buon fine

DOS / Batch file: sc qc

sc qc SgartNet5WorkerService

da un risultato simile a questo

Text

[SC] QueryServiceConfig SUCCESS

SERVICE_NAME: SgartNet5WorkerService
        TYPE               : 10  WIN32_OWN_PROCESS
        START_TYPE         : 3   DEMAND_START
        ERROR_CONTROL      : 1   NORMAL
        BINARY_PATH_NAME   : C:\...\Sgart.Net5.WorkerService.exe
        LOAD_ORDER_GROUP   :
        TAG                : 0
        DISPLAY_NAME       : SgartNet5WorkerService
        DEPENDENCIES       :
        SERVICE_START_NAME : LocalSystem

Installazione in PowerShell

L'installazione può essere fatta anche con PowerShell tramite i seguenti comandi

PowerShell: Install

$params = @{ 
  Name = "SgartNet5WorkerService" 
  BinaryPathName = 'C:\...\Sgart.Net5.WorkerService.exe'
  DisplayName = "Sgart Demo Service"
  StartupType = "Manual" 
  Description = "Sgart.it servizio demo in .NET 5" 
} 
New-Service @params

PowerShell: Start e Stop

Start-Service SgartNet5WorkerService 

Stop-Service SgartNet5WorkerService

PowerShell: Status

Get-Service SgartNet5WorkerService | select *

Demo

Vedi l'esempio completo su GitHub - Sgart.Net5.WorkerService.
Tags:
.NET 55 .NET Core26 PowerShell201
Potrebbe interessarti anche: