using System; // ============================================================================================== // For testing windows service with .NET 5 // Source: https://stackoverflow.com/questions/7764088/net-console-application-as-windows-service // ============================================================================================== using System.ServiceProcess; using System.IO; public static class Program { #region Nested classes to support running as service public const string ServiceName = "MyService"; public class Service : ServiceBase { public Service() { File.AppendAllLines("log.txt", new string[] { "Service init" }); ServiceName = Program.ServiceName; } protected override void OnStart(string[] args) { File.AppendAllLines("log.txt", new string[] { "Service start" }); Program.Start(args); base.OnStart(args); } protected override void OnStop() { File.AppendAllLines("log.txt", new string[] { "Service stop" }); Program.Stop(); base.OnStop(); } } #endregion static void Main(string[] args) { File.AppendAllLines("log.txt", new string[] { "App init" }); if (!Environment.UserInteractive) { File.AppendAllLines("log.txt", new string[] { "Running as service" }); // running as service using (var service = new Service()) ServiceBase.Run(service); } else { File.AppendAllLines("log.txt", new string[] { "Running as app" }); // running as console app Start(args); Console.WriteLine("Press any key to stop..."); Console.ReadKey(true); Stop(); } } private static void Start(string[] args) { // onstart code here } private static void Stop() { // onstop code here } }