diff --git a/Source/PeterKottas.DotNetCore.WindowsService.Example/ExampleService.cs b/Source/PeterKottas.DotNetCore.WindowsService.Example/ExampleService.cs index 7f1c2e0..b3c8bf7 100644 --- a/Source/PeterKottas.DotNetCore.WindowsService.Example/ExampleService.cs +++ b/Source/PeterKottas.DotNetCore.WindowsService.Example/ExampleService.cs @@ -8,45 +8,45 @@ namespace PeterKottas.DotNetCore.WindowsService.Example { public class ExampleService : IMicroService { - private IMicroServiceController controller; + private IMicroServiceController _controller; - private Timer timer = new Timer(1000); + private readonly Timer _timer = new Timer(1000); + private readonly string _fileName = Path.Combine(PlatformServices.Default.Application.ApplicationBasePath, "log.txt"); public ExampleService() { - controller = null; + _controller = null; } public ExampleService(IMicroServiceController controller) { - this.controller = controller; + _controller = controller; } - private string fileName = Path.Combine(PlatformServices.Default.Application.ApplicationBasePath, "log.txt"); public void Start() { Console.WriteLine("I started"); - Console.WriteLine(fileName); - File.AppendAllText(fileName, "Started\n"); + Console.WriteLine(_fileName); + File.AppendAllText(_fileName, "Started\n"); /** * A timer is a simple example. But this could easily * be a port or messaging queue client */ - timer.Elapsed += _timer_Elapsed; - timer.Start(); + _timer.Elapsed += _timer_Elapsed; + _timer.Start(); } - private void _timer_Elapsed(object sender, ElapsedEventArgs e) - { - File.AppendAllText(fileName, string.Format("Polling at {0}\n", DateTime.Now.ToString("o"))); - } - public void Stop() { - timer.Stop(); - File.AppendAllText(fileName, "Stopped\n"); + _timer.Stop(); + File.AppendAllText(_fileName, "Stopped\n"); Console.WriteLine("I stopped"); } + + private void _timer_Elapsed(object sender, ElapsedEventArgs e) + { + File.AppendAllText(_fileName, string.Format("Polling at {0}\n", DateTime.Now.ToString("o"))); + } } } diff --git a/Source/PeterKottas.DotNetCore.WindowsService.Example/ExampleServiceTimer.cs b/Source/PeterKottas.DotNetCore.WindowsService.Example/ExampleServiceTimer.cs index 0bc96ed..64e12e5 100644 --- a/Source/PeterKottas.DotNetCore.WindowsService.Example/ExampleServiceTimer.cs +++ b/Source/PeterKottas.DotNetCore.WindowsService.Example/ExampleServiceTimer.cs @@ -9,6 +9,7 @@ namespace PeterKottas.DotNetCore.WindowsService.Example public class ExampleServiceTimer : MicroService, IMicroService { private IMicroServiceController controller; + private readonly string _fileName = Path.Combine(PlatformServices.Default.Application.ApplicationBasePath, "log.txt"); public ExampleServiceTimer() { @@ -20,22 +21,21 @@ public ExampleServiceTimer(IMicroServiceController controller) this.controller = controller; } - private string fileName = Path.Combine(PlatformServices.Default.Application.ApplicationBasePath, "log.txt"); public void Start() { StartBase(); Timers.Start("Poller", 1000, () => { - File.AppendAllText(fileName, string.Format("Polling at {0}\n", DateTime.Now.ToString("o"))); + File.AppendAllText(_fileName, string.Format("Polling at {0}\n", DateTime.Now.ToString("o"))); }); Console.WriteLine("I started"); - File.AppendAllText(fileName, "Started\n"); + File.AppendAllText(_fileName, "Started\n"); } public void Stop() { StopBase(); - File.AppendAllText(fileName, "Stopped\n"); + File.AppendAllText(_fileName, "Stopped\n"); Console.WriteLine("I stopped"); } } diff --git a/Source/PeterKottas.DotNetCore.WindowsService/Base/MicroService.cs b/Source/PeterKottas.DotNetCore.WindowsService/Base/MicroService.cs index ea3c133..7a99d64 100644 --- a/Source/PeterKottas.DotNetCore.WindowsService/Base/MicroService.cs +++ b/Source/PeterKottas.DotNetCore.WindowsService/Base/MicroService.cs @@ -1,15 +1,11 @@ -using PeterKottas.DotNetCore.WindowsService.Interfaces; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; +using System; namespace PeterKottas.DotNetCore.WindowsService.Base { public class MicroService : IDisposable { protected Timers Timers { get; private set; } - private bool disposed = false; + private bool _disposed; public void StartBase() { @@ -32,7 +28,7 @@ public void Dispose() protected virtual void Dispose(bool disposing) { - if (disposed) + if (_disposed) return; if (disposing) @@ -40,7 +36,7 @@ protected virtual void Dispose(bool disposing) StopBase(); } - disposed = true; + _disposed = true; } ~MicroService() diff --git a/Source/PeterKottas.DotNetCore.WindowsService/Base/Timer.cs b/Source/PeterKottas.DotNetCore.WindowsService/Base/Timer.cs index 5473ea3..4b8b7cd 100644 --- a/Source/PeterKottas.DotNetCore.WindowsService/Base/Timer.cs +++ b/Source/PeterKottas.DotNetCore.WindowsService/Base/Timer.cs @@ -1,8 +1,5 @@ using System; -using System.Collections.Generic; -using System.Linq; using System.Threading; -using System.Threading.Tasks; namespace PeterKottas.DotNetCore.WindowsService.Base { @@ -11,10 +8,10 @@ namespace PeterKottas.DotNetCore.WindowsService.Base /// public class Timer { - private Thread thread; - private AutoResetEvent stopRequest; - private bool running = true; - private bool paused = false; + private Thread _thread; + private AutoResetEvent _stopRequest; + private bool _running = true; + private bool _paused; public Action OnTimer { get; set; } @@ -26,38 +23,38 @@ public class Timer public Timer(string name, int interval, Action onTimer, Action onException = null) { - this.OnTimer = onTimer == null ? () => { } : onTimer; ; - this.Name = name; - this.Interval = interval; - this.OnException = onException == null ? (e) => { } : onException; + OnTimer = onTimer == null ? () => { } : onTimer; ; + Name = name; + Interval = interval; + OnException = onException == null ? (e) => { } : onException; } private void InternalWork(object arg) { - while (running) + while (_running) { try { - if (!paused) + if (!_paused) { - this.OnTimer(); + OnTimer(); } } catch (Exception exception) { - this.OnException(exception); + OnException(exception); } try { - if (stopRequest.WaitOne(Interval)) + if (_stopRequest.WaitOne(Interval)) { return; } } catch (Exception exception) { - this.OnException(exception); + OnException(exception); } } @@ -65,34 +62,34 @@ private void InternalWork(object arg) public void Start() { - stopRequest = new AutoResetEvent(false); - running = true; - thread = new Thread(InternalWork); - thread.Start(); + _stopRequest = new AutoResetEvent(false); + _running = true; + _thread = new Thread(InternalWork); + _thread.Start(); } public void Pause() { - paused = true; + _paused = true; } public void Resume() { - paused = false; + _paused = false; } public void Stop() { - if (running) - { - running = false; - stopRequest.Set(); - thread.Join(); + if (!_running) + return; - thread = null; - stopRequest.Dispose(); - stopRequest = null; - } + _running = false; + _stopRequest.Set(); + _thread.Join(); + + _thread = null; + _stopRequest.Dispose(); + _stopRequest = null; } } } diff --git a/Source/PeterKottas.DotNetCore.WindowsService/Base/Timers.cs b/Source/PeterKottas.DotNetCore.WindowsService/Base/Timers.cs index 80899e5..0fad243 100644 --- a/Source/PeterKottas.DotNetCore.WindowsService/Base/Timers.cs +++ b/Source/PeterKottas.DotNetCore.WindowsService/Base/Timers.cs @@ -1,21 +1,21 @@ using System; using System.Collections.Generic; using System.Linq; -using System.Threading.Tasks; namespace PeterKottas.DotNetCore.WindowsService.Base { public class Timers { - List timers = new List(); + private readonly List _timers = new List(); public void Start(string timerName, int interval, Action onTimer, Action onException = null) { - var tmpTimer = timers.Where(x => x.Name == timerName).FirstOrDefault(); + var tmpTimer = _timers.FirstOrDefault(x => x.Name == timerName); + if (tmpTimer == null) { tmpTimer = new Timer(timerName, interval, onTimer, onException); - timers.Add(tmpTimer); + _timers.Add(tmpTimer); tmpTimer.Start(); } @@ -29,27 +29,28 @@ public void Start(string timerName, int interval, Action onTimer, Action onException = null) { - var tmpTimer = timers.Where(x => x.Name == timerName).FirstOrDefault(); - if (tmpTimer != null) + var tmpTimer = _timers.FirstOrDefault(x => x.Name == timerName); + + if (tmpTimer == null) + return; + + if (onTimer != null) + { + tmpTimer.OnTimer = onTimer; + } + if (onException != null) + { + tmpTimer.OnException = onException; + } + if (interval > 0 && interval != tmpTimer.Interval) { - if (onTimer != null) - { - tmpTimer.OnTimer = onTimer; - } - if (onException != null) - { - tmpTimer.OnException = onException; - } - if (interval > 0 && interval != tmpTimer.Interval) - { - tmpTimer.Interval = interval; - } + tmpTimer.Interval = interval; } } public void Resume() { - foreach (var timer in timers) + foreach (var timer in _timers) { timer.Resume(); } @@ -57,7 +58,8 @@ public void Resume() public void Resume(string timerName) { - var tmpTimer = timers.Where(x => x.Name == timerName).FirstOrDefault(); + var tmpTimer = _timers.FirstOrDefault(x => x.Name == timerName); + if (tmpTimer != null) { tmpTimer.Resume(); @@ -66,7 +68,7 @@ public void Resume(string timerName) public void Pause() { - foreach (var timer in timers) + foreach (var timer in _timers) { timer.Pause(); } @@ -74,7 +76,8 @@ public void Pause() public void Pause(string timerName) { - var tmpTimer = timers.Where(x => x.Name == timerName).FirstOrDefault(); + var tmpTimer = _timers.FirstOrDefault(x => x.Name == timerName); + if (tmpTimer != null) { tmpTimer.Pause(); @@ -83,7 +86,7 @@ public void Pause(string timerName) public void Stop() { - foreach (var timer in timers) + foreach (var timer in _timers) { timer.Stop(); } @@ -91,7 +94,8 @@ public void Stop() public void Stop(string timerName) { - var tmpTimer = timers.Where(x => x.Name == timerName).FirstOrDefault(); + var tmpTimer = _timers.FirstOrDefault(x => x.Name == timerName); + if (tmpTimer != null) { tmpTimer.Stop(); diff --git a/Source/PeterKottas.DotNetCore.WindowsService/Configurators/Service/ServiceConfigurator.cs b/Source/PeterKottas.DotNetCore.WindowsService/Configurators/Service/ServiceConfigurator.cs index 26889e6..b99f50c 100644 --- a/Source/PeterKottas.DotNetCore.WindowsService/Configurators/Service/ServiceConfigurator.cs +++ b/Source/PeterKottas.DotNetCore.WindowsService/Configurators/Service/ServiceConfigurator.cs @@ -4,57 +4,58 @@ namespace PeterKottas.DotNetCore.WindowsService.Configurators.Service { - public class ServiceConfigurator where SERVICE : IMicroService + public class ServiceConfigurator where TService : IMicroService { - private HostConfiguration config; - public ServiceConfigurator(HostConfiguration config) + private readonly HostConfiguration _config; + + public ServiceConfigurator(HostConfiguration config) { - this.config = config; + _config = config; } - public void ServiceFactory(Func, IMicroServiceController, SERVICE> serviceFactory) + public void ServiceFactory(Func, IMicroServiceController, TService> serviceFactory) { - config.ServiceFactory = serviceFactory; + _config.ServiceFactory = serviceFactory; } - public void OnStart(Action> onStart) + public void OnStart(Action> onStart) { - config.OnServiceStart = onStart; + _config.OnServiceStart = onStart; } - public void OnStop(Action onStop) + public void OnStop(Action onStop) { - config.OnServiceStop = onStop; + _config.OnServiceStop = onStop; } public void OnError(Action onError) { - config.OnServiceError = onError; + _config.OnServiceError = onError; } - public void OnPause(Action onPause) + public void OnPause(Action onPause) { - config.OnServicePause = onPause; + _config.OnServicePause = onPause; } - public void OnInstall(Action onInstall) + public void OnInstall(Action onInstall) { - config.OnServiceInstall = onInstall; + _config.OnServiceInstall = onInstall; } - public void OnUnInstall(Action onUnInstall) + public void OnUnInstall(Action onUnInstall) { - config.OnServiceUnInstall = onUnInstall; + _config.OnServiceUnInstall = onUnInstall; } - public void OnContinue(Action onContinue) + public void OnContinue(Action onContinue) { - config.OnServiceContinue = onContinue; + _config.OnServiceContinue = onContinue; } - public void OnShutdown(Action onShutdown) + public void OnShutdown(Action onShutdown) { - config.OnServiceShutdown = onShutdown; + _config.OnServiceShutdown = onShutdown; } } } \ No newline at end of file diff --git a/Source/PeterKottas.DotNetCore.WindowsService/ConsoleServiceHost.cs b/Source/PeterKottas.DotNetCore.WindowsService/ConsoleServiceHost.cs index 677453a..c6dbb4c 100644 --- a/Source/PeterKottas.DotNetCore.WindowsService/ConsoleServiceHost.cs +++ b/Source/PeterKottas.DotNetCore.WindowsService/ConsoleServiceHost.cs @@ -9,16 +9,16 @@ namespace PeterKottas.DotNetCore.WindowsService /// Copy of Topshelf ConsoleRunHost /// https://github.com/Topshelf/Topshelf/blob/develop/src/Topshelf/Hosts/ConsoleRunHost.cs /// - class ConsoleServiceHost - where SERVICE : IMicroService + class ConsoleServiceHost + where TService : IMicroService { - private InnerService _consoleService = null; - private HostConfiguration _innerConfig = null; + private readonly InnerService _consoleService; + private readonly HostConfiguration _innerConfig; private ExitCode _exitCode = 0; - private ManualResetEvent _exit = null; - private volatile bool _hasCancelled = false; + private ManualResetEvent _exit; + private volatile bool _hasCancelled; - public ConsoleServiceHost(InnerService consoleService, HostConfiguration innerConfig) + public ConsoleServiceHost(InnerService consoleService, HostConfiguration innerConfig) { _consoleService = consoleService ?? throw new ArgumentNullException(nameof(consoleService)); @@ -32,6 +32,7 @@ internal ExitCode Run() AppDomain.CurrentDomain.UnhandledException += CatchUnhandledException; bool started = false; + try { Console.WriteLine("Starting up as a console service host"); @@ -77,6 +78,7 @@ internal void StopService() Console.WriteLine("Stopping the {0} service", _consoleService.ServiceName); Task stopTask = Task.Run(() => _consoleService.Stop()); + if (!stopTask.Wait(TimeSpan.FromMilliseconds(_innerConfig.ServiceTimeout))) throw new Exception("The service failed to stop (returned false)."); @@ -109,6 +111,7 @@ private void HandleCancelKeyPress(object sender, ConsoleCancelEventArgs e) Console.WriteLine("Control+C detected, attempting to stop service."); Task stopTask = Task.Run(() => _consoleService.Stop()); + if (stopTask.Wait(TimeSpan.FromMilliseconds(_innerConfig.ConsoleTimeout))) { _hasCancelled = true; @@ -123,7 +126,7 @@ private void HandleCancelKeyPress(object sender, ConsoleCancelEventArgs e) private void CatchUnhandledException(object sender, UnhandledExceptionEventArgs e) { - Console.WriteLine("The service threw an unhandled exception: {0}", e.ToString()); + Console.WriteLine("The service threw an unhandled exception: {0}", e); if (!e.IsTerminating) return; diff --git a/Source/PeterKottas.DotNetCore.WindowsService/Enums/ActionEnum.cs b/Source/PeterKottas.DotNetCore.WindowsService/Enums/ActionEnum.cs index 9745041..5855257 100644 --- a/Source/PeterKottas.DotNetCore.WindowsService/Enums/ActionEnum.cs +++ b/Source/PeterKottas.DotNetCore.WindowsService/Enums/ActionEnum.cs @@ -1,9 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; - -namespace PeterKottas.DotNetCore.WindowsService.Enums +namespace PeterKottas.DotNetCore.WindowsService.Enums { public enum ActionEnum { diff --git a/Source/PeterKottas.DotNetCore.WindowsService/HostConfiguration.cs b/Source/PeterKottas.DotNetCore.WindowsService/HostConfiguration.cs index 7a5de76..27aef4e 100644 --- a/Source/PeterKottas.DotNetCore.WindowsService/HostConfiguration.cs +++ b/Source/PeterKottas.DotNetCore.WindowsService/HostConfiguration.cs @@ -1,14 +1,12 @@ using System; using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; using PeterKottas.DotNetCore.WindowsService.Enums; using PeterKottas.DotNetCore.WindowsService.Interfaces; using DasMulli.Win32.ServiceUtils; namespace PeterKottas.DotNetCore.WindowsService { - public class HostConfiguration where SERVICE : IMicroService + public class HostConfiguration where TService : IMicroService { public HostConfiguration() { @@ -40,23 +38,23 @@ public HostConfiguration() public Win32ServiceCredentials DefaultCred { get; set; } = Win32ServiceCredentials.LocalSystem; - public SERVICE Service { get; set; } + public TService Service { get; set; } - public Func, IMicroServiceController, SERVICE> ServiceFactory { get; set; } + public Func, IMicroServiceController, TService> ServiceFactory { get; set; } - public Action> OnServiceStart { get; set; } + public Action> OnServiceStart { get; set; } - public Action OnServiceStop { get; set; } + public Action OnServiceStop { get; set; } - public Action OnServiceInstall { get; set; } + public Action OnServiceInstall { get; set; } - public Action OnServiceUnInstall { get; set; } + public Action OnServiceUnInstall { get; set; } - public Action OnServicePause { get; set; } + public Action OnServicePause { get; set; } - public Action OnServiceContinue { get; set; } + public Action OnServiceContinue { get; set; } - public Action OnServiceShutdown { get; set; } + public Action OnServiceShutdown { get; set; } public Action OnServiceError { get; set; } diff --git a/Source/PeterKottas.DotNetCore.WindowsService/HostConfigurator.cs b/Source/PeterKottas.DotNetCore.WindowsService/HostConfigurator.cs index c6e3a77..d093698 100644 --- a/Source/PeterKottas.DotNetCore.WindowsService/HostConfigurator.cs +++ b/Source/PeterKottas.DotNetCore.WindowsService/HostConfigurator.cs @@ -1,64 +1,62 @@ using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; using PeterKottas.DotNetCore.WindowsService.Configurators.Service; using PeterKottas.DotNetCore.WindowsService.Interfaces; namespace PeterKottas.DotNetCore.WindowsService { - public class HostConfigurator where SERVICE : IMicroService + public class HostConfigurator where TService : IMicroService { - HostConfiguration innerConfig; - public HostConfigurator(HostConfiguration innerConfig) + private readonly HostConfiguration _innerConfig; + + public HostConfigurator(HostConfiguration innerConfig) { - this.innerConfig = innerConfig; + _innerConfig = innerConfig; } public void SetName(string serviceName, bool force = false) { - if (!string.IsNullOrEmpty(innerConfig.Name) || force) + if (!string.IsNullOrEmpty(_innerConfig.Name) || force) { - innerConfig.Name = serviceName; + _innerConfig.Name = serviceName; } } public void SetDisplayName(string displayName, bool force = false) { - if (!string.IsNullOrEmpty(innerConfig.DisplayName) || force) + if (!string.IsNullOrEmpty(_innerConfig.DisplayName) || force) { - innerConfig.DisplayName = displayName; + _innerConfig.DisplayName = displayName; } } public void SetDescription(string description, bool force = false) { - if (!string.IsNullOrEmpty(innerConfig.Description) || force) + if (!string.IsNullOrEmpty(_innerConfig.Description) || force) { - innerConfig.Description = description; + _innerConfig.Description = description; } } public void SetConsoleTimeout(int milliseconds) { - innerConfig.ConsoleTimeout = milliseconds; + _innerConfig.ConsoleTimeout = milliseconds; } public void SetServiceTimeout(int milliseconds) { - innerConfig.ServiceTimeout = milliseconds; + _innerConfig.ServiceTimeout = milliseconds; } public string GetDefaultName() { - return innerConfig.Name; + return _innerConfig.Name; } public bool IsNameNullOrEmpty { get { - return string.IsNullOrEmpty(innerConfig.Name); + return string.IsNullOrEmpty(_innerConfig.Name); } } @@ -66,7 +64,7 @@ public bool IsDescriptionNullOrEmpty { get { - return string.IsNullOrEmpty(innerConfig.Description); + return string.IsNullOrEmpty(_innerConfig.Description); } } @@ -74,24 +72,26 @@ public bool IsDisplayNameNullOrEmpty { get { - return string.IsNullOrEmpty(innerConfig.DisplayName); + return string.IsNullOrEmpty(_innerConfig.DisplayName); } } - public void Service(Action> serviceConfigAction) + public void Service(Action> serviceConfigAction) { try { - var serviceConfig = new ServiceConfigurator(innerConfig); + var serviceConfig = new ServiceConfigurator(_innerConfig); + serviceConfigAction(serviceConfig); - if (innerConfig.ServiceFactory == null) + + if (_innerConfig.ServiceFactory == null) { - throw new ArgumentException("It's necesarry to configure action that creates the service (ServiceFactory)"); + throw new ArgumentException("It's necessary to configure action that creates the service (ServiceFactory)"); } - if (innerConfig.OnServiceStart == null) + if (_innerConfig.OnServiceStart == null) { - throw new ArgumentException("It's necesarry to configure action that is called when the service starts"); + throw new ArgumentException("It's necessary to configure action that is called when the service starts"); } } catch (Exception e) diff --git a/Source/PeterKottas.DotNetCore.WindowsService/InnerService.cs b/Source/PeterKottas.DotNetCore.WindowsService/InnerService.cs index b3ca7ae..b74d308 100644 --- a/Source/PeterKottas.DotNetCore.WindowsService/InnerService.cs +++ b/Source/PeterKottas.DotNetCore.WindowsService/InnerService.cs @@ -1,56 +1,53 @@ using DasMulli.Win32.ServiceUtils; using PeterKottas.DotNetCore.WindowsService.Interfaces; using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; namespace PeterKottas.DotNetCore.WindowsService { public class InnerService : IShutdownableWin32Service { - string serviceName; - Action onStart; - Action onStopped; - Action onShutdown; + private readonly string _serviceName; + private readonly Action _onStart; + private readonly Action _onStopped; + private readonly Action _onShutdown; public InnerService(string serviceName, Action onStart, Action onStopped, Action onShutdown) { - this.serviceName = serviceName; - this.onStart = onStart; - this.onStopped = onStopped; - this.onShutdown = onShutdown; + _serviceName = serviceName; + _onStart = onStart; + _onStopped = onStopped; + _onShutdown = onShutdown; } public string ServiceName { get { - return serviceName; + return _serviceName; } } public void Shutdown() { - onShutdown(); + _onShutdown(); } public void Start(string[] startupArguments, ServiceStoppedCallback serviceStoppedCallback) { try { - onStart(); + _onStart(); } catch (Exception) { - onStopped(); + _onStopped(); serviceStoppedCallback(); } } public void Stop() { - onStopped(); + _onStopped(); } } } diff --git a/Source/PeterKottas.DotNetCore.WindowsService/Interfaces/IMicroService.cs b/Source/PeterKottas.DotNetCore.WindowsService/Interfaces/IMicroService.cs index 22570ce..841b844 100644 --- a/Source/PeterKottas.DotNetCore.WindowsService/Interfaces/IMicroService.cs +++ b/Source/PeterKottas.DotNetCore.WindowsService/Interfaces/IMicroService.cs @@ -1,9 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; - -namespace PeterKottas.DotNetCore.WindowsService.Interfaces +namespace PeterKottas.DotNetCore.WindowsService.Interfaces { public interface IMicroService { diff --git a/Source/PeterKottas.DotNetCore.WindowsService/Interfaces/IMicroServiceController.cs b/Source/PeterKottas.DotNetCore.WindowsService/Interfaces/IMicroServiceController.cs index 240efcb..16508bc 100644 --- a/Source/PeterKottas.DotNetCore.WindowsService/Interfaces/IMicroServiceController.cs +++ b/Source/PeterKottas.DotNetCore.WindowsService/Interfaces/IMicroServiceController.cs @@ -1,8 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace PeterKottas.DotNetCore.WindowsService.Interfaces +namespace PeterKottas.DotNetCore.WindowsService.Interfaces { public interface IMicroServiceController { diff --git a/Source/PeterKottas.DotNetCore.WindowsService/Interfaces/IShutdownableWin32Service.cs b/Source/PeterKottas.DotNetCore.WindowsService/Interfaces/IShutdownableWin32Service.cs index 51b6db9..fa18e0c 100644 --- a/Source/PeterKottas.DotNetCore.WindowsService/Interfaces/IShutdownableWin32Service.cs +++ b/Source/PeterKottas.DotNetCore.WindowsService/Interfaces/IShutdownableWin32Service.cs @@ -1,7 +1,4 @@ using DasMulli.Win32.ServiceUtils; -using System; -using System.Collections.Generic; -using System.Text; namespace PeterKottas.DotNetCore.WindowsService.Interfaces { diff --git a/Source/PeterKottas.DotNetCore.WindowsService/MicroServiceController.cs b/Source/PeterKottas.DotNetCore.WindowsService/MicroServiceController.cs index 0c71427..795f45c 100644 --- a/Source/PeterKottas.DotNetCore.WindowsService/MicroServiceController.cs +++ b/Source/PeterKottas.DotNetCore.WindowsService/MicroServiceController.cs @@ -1,23 +1,20 @@ using PeterKottas.DotNetCore.WindowsService.Interfaces; using System; -using System.Collections.Generic; -using System.Text; -using System.Threading.Tasks; namespace PeterKottas.DotNetCore.WindowsService { public class MicroServiceController : IMicroServiceController { - private Action stop; + private readonly Action _stop; public MicroServiceController(Action stop) { - this.stop = stop; + _stop = stop; } public void Stop() { - stop(); + _stop(); } } } diff --git a/Source/PeterKottas.DotNetCore.WindowsService/ServiceRunner.cs b/Source/PeterKottas.DotNetCore.WindowsService/ServiceRunner.cs index c30c514..f6cad41 100644 --- a/Source/PeterKottas.DotNetCore.WindowsService/ServiceRunner.cs +++ b/Source/PeterKottas.DotNetCore.WindowsService/ServiceRunner.cs @@ -14,19 +14,21 @@ namespace PeterKottas.DotNetCore.WindowsService { - public static class ServiceRunner where SERVICE : IMicroService + public static class ServiceRunner where TService : IMicroService { - public static int Run(Action> runAction) + public static int Run(Action> runAction) { Directory.SetCurrentDirectory(PlatformServices.Default.Application.ApplicationBasePath); - var innerConfig = new HostConfiguration(); - innerConfig.Action = ActionEnum.RunInteractive; - innerConfig.Name = typeof(SERVICE).FullName; + var innerConfig = new HostConfiguration + { + Action = ActionEnum.RunInteractive, + Name = typeof(TService).FullName + }; innerConfig.ExtraArguments = Parser.Parse(config => { - config.AddParameter(new CmdArgParam() + config.AddParameter(new CmdArgParam { Key = "username", Description = "Username for the service account", @@ -35,7 +37,7 @@ public static int Run(Action> runAction) innerConfig.Username = val; } }); - config.AddParameter(new CmdArgParam() + config.AddParameter(new CmdArgParam { Key = "password", Description = "Password for the service account", @@ -44,7 +46,7 @@ public static int Run(Action> runAction) innerConfig.Password = val; } }); - config.AddParameter(new CmdArgParam() + config.AddParameter(new CmdArgParam { Key = "built-in-account", Description = "Password for the service account", @@ -68,7 +70,7 @@ public static int Run(Action> runAction) } }); - config.AddParameter(new CmdArgParam() + config.AddParameter(new CmdArgParam { Key = "start-immediately", Description = "Start the service immediately when installing.", @@ -80,7 +82,7 @@ public static int Run(Action> runAction) } } }); - config.AddParameter(new CmdArgParam() + config.AddParameter(new CmdArgParam { Key = "name", Description = "Service name", @@ -89,7 +91,7 @@ public static int Run(Action> runAction) innerConfig.Name = val; } }); - config.AddParameter(new CmdArgParam() + config.AddParameter(new CmdArgParam { Key = "description", Description = "Service description", @@ -98,7 +100,7 @@ public static int Run(Action> runAction) innerConfig.Description = val; } }); - config.AddParameter(new CmdArgParam() + config.AddParameter(new CmdArgParam { Key = "display-name", Description = "Service display name", @@ -107,7 +109,7 @@ public static int Run(Action> runAction) innerConfig.DisplayName = val; } }); - config.AddParameter(new CmdArgParam() + config.AddParameter(new CmdArgParam { Key = "action", Description = "Installs the service. It's run like console application otherwise", @@ -153,7 +155,7 @@ public static int Run(Action> runAction) if (string.IsNullOrEmpty(innerConfig.Name)) { - innerConfig.Name = typeof(SERVICE).FullName; + innerConfig.Name = typeof(TService).FullName; } if (string.IsNullOrEmpty(innerConfig.DisplayName)) @@ -166,34 +168,37 @@ public static int Run(Action> runAction) innerConfig.Description = "No description"; } - var hostConfiguration = new HostConfigurator(innerConfig); + var hostConfiguration = new HostConfigurator(innerConfig); try { runAction(hostConfiguration); + if (innerConfig.Action == ActionEnum.Run) + { innerConfig.Service = innerConfig.ServiceFactory(innerConfig.ExtraArguments, new MicroServiceController(() => - { - var task = Task.Factory.StartNew(() => { - UsingServiceController(innerConfig, (sc, cfg) => StopService(cfg, sc)); - }); - } - )); + Task.Factory.StartNew(() => + { + UsingServiceController(innerConfig, (sc, cfg) => StopService(cfg, sc)); + }); + } + )); + } else if (innerConfig.Action == ActionEnum.RunInteractive) { var consoleService = new InnerService(innerConfig.Name, () => Start(innerConfig), () => Stop(innerConfig), () => Shutdown(innerConfig)); - var consoleHost = new ConsoleServiceHost(consoleService, innerConfig); + var consoleHost = new ConsoleServiceHost(consoleService, innerConfig); innerConfig.Service = innerConfig.ServiceFactory(innerConfig.ExtraArguments, new MicroServiceController(() => - { - var task = Task.Factory.StartNew(() => { - consoleHost.StopService(); - }); - } + Task.Factory.StartNew(() => + { + consoleHost.StopService(); + }); + } )); // Return the console host run result, so we get some idea what failed if result is not OK @@ -211,6 +216,7 @@ public static int Run(Action> runAction) catch (Exception e) { Error(innerConfig, e); + return -1; } } @@ -218,10 +224,12 @@ public static int Run(Action> runAction) private static string GetServiceCommand(List extraArguments) { var host = Process.GetCurrentProcess().MainModule.FileName; + if (host.EndsWith("dotnet.exe", StringComparison.OrdinalIgnoreCase)) { var appPath = Path.Combine(PlatformServices.Default.Application.ApplicationBasePath, PlatformServices.Default.Application.ApplicationName + ".dll"); + host = string.Format("{0} \"{1}\"", host, appPath); } else @@ -231,16 +239,19 @@ private static string GetServiceCommand(List extraArguments) } var fullServiceCommand = string.Format("{0} {1} {2}", host, string.Join(" ", extraArguments), "action:run"); + return fullServiceCommand; } - private static void Install(HostConfiguration config, ServiceController sc, int counter = 0) + private static void Install(HostConfiguration config, ServiceController sc, int counter = 0) { Win32ServiceCredentials cred = config.DefaultCred; + if (!string.IsNullOrEmpty(config.Username)) { cred = new Win32ServiceCredentials(config.Username, config.Password); } + try { new Win32ServiceManager().CreateService(new ServiceDefinition(config.Name, GetServiceCommand(config.ExtraArguments)) @@ -252,6 +263,7 @@ private static void Install(HostConfiguration config, ServiceController DelayedAutoStart = !config.StartImmediately, ErrorSeverity = ErrorSeverity.Normal }); + Console.WriteLine($@"Successfully registered and started service ""{config.Name}"" (""{config.Description}"")"); } catch (Exception e) @@ -268,6 +280,7 @@ private static void Install(HostConfiguration config, ServiceController System.Threading.Thread.Sleep(500); counter++; string suffix = "th"; + if (counter == 1) { suffix = "st"; @@ -280,6 +293,7 @@ private static void Install(HostConfiguration config, ServiceController { suffix = "rd"; } + Console.WriteLine("The specified service has been marked for deletion. Retrying {0}{1} time", counter, suffix); Install(config, sc, counter); } @@ -295,7 +309,7 @@ private static void Install(HostConfiguration config, ServiceController } } - private static void Uninstall(HostConfiguration config, ServiceController sc) + private static void Uninstall(HostConfiguration config, ServiceController sc) { try { @@ -303,6 +317,7 @@ private static void Uninstall(HostConfiguration config, ServiceControll { StopService(config, sc); } + new Win32ServiceManager().DeleteService(config.Name); Console.WriteLine($@"Successfully unregistered service ""{config.Name}"" (""{config.Description}"")"); config.OnServiceUnInstall?.Invoke(config.Service); @@ -313,11 +328,12 @@ private static void Uninstall(HostConfiguration config, ServiceControll { throw; } + Console.WriteLine($@"Service ""{config.Name}"" (""{config.Description}"") does not exist. No action taken."); } } - private static void StopService(HostConfiguration config, ServiceController sc) + private static void StopService(HostConfiguration config, ServiceController sc) { if (!(sc.Status == ServiceControllerStatus.Stopped | sc.Status == ServiceControllerStatus.StopPending)) { @@ -332,7 +348,7 @@ private static void StopService(HostConfiguration config, ServiceContro } } - private static void PauseService(HostConfiguration config, ServiceController sc) + private static void PauseService(HostConfiguration config, ServiceController sc) { if (!(sc.Status == ServiceControllerStatus.Paused | sc.Status == ServiceControllerStatus.PausePending)) { @@ -347,7 +363,7 @@ private static void PauseService(HostConfiguration config, ServiceContr } } - private static void ContinueService(HostConfiguration config, ServiceController sc) + private static void ContinueService(HostConfiguration config, ServiceController sc) { if (!(sc.Status == ServiceControllerStatus.Running | sc.Status == ServiceControllerStatus.ContinuePending)) { @@ -362,7 +378,7 @@ private static void ContinueService(HostConfiguration config, ServiceCo } } - private static void StartService(HostConfiguration config, ServiceController sc) + private static void StartService(HostConfiguration config, ServiceController sc) { if (!(sc.Status == ServiceControllerStatus.StartPending | sc.Status == ServiceControllerStatus.Running)) { @@ -376,14 +392,14 @@ private static void StartService(HostConfiguration config, ServiceContr } } - private static void Reinstall(HostConfiguration config, ServiceController sc) + private static void Reinstall(HostConfiguration config, ServiceController sc) { StopService(config, sc); Uninstall(config, sc); Install(config, sc); } - private static void ConfigureService(HostConfiguration config) + private static void ConfigureService(HostConfiguration config) { switch (config.Action) { @@ -415,7 +431,7 @@ private static void ConfigureService(HostConfiguration config) } } - private static void UsingServiceController(HostConfiguration config, Action> action) + private static void UsingServiceController(HostConfiguration config, Action> action) { using (var sc = new ServiceController(config.Name)) { @@ -423,7 +439,7 @@ private static void UsingServiceController(HostConfiguration config, Ac } } - private static void Start(HostConfiguration config) + private static void Start(HostConfiguration config) { try { @@ -435,7 +451,7 @@ private static void Start(HostConfiguration config) } } - private static void Stop(HostConfiguration config) + private static void Stop(HostConfiguration config) { try { @@ -447,7 +463,7 @@ private static void Stop(HostConfiguration config) } } - private static void Shutdown(HostConfiguration config) + private static void Shutdown(HostConfiguration config) { try { @@ -459,7 +475,7 @@ private static void Shutdown(HostConfiguration config) } } - private static void Error(HostConfiguration config, Exception e = null) + private static void Error(HostConfiguration config, Exception e = null) { config.OnServiceError(e); } diff --git a/Source/PeterKottas.DotNetCore.WindowsService/StateMachines/ShutdownableServiceStateMachine.cs b/Source/PeterKottas.DotNetCore.WindowsService/StateMachines/ShutdownableServiceStateMachine.cs index e67011c..638fc99 100644 --- a/Source/PeterKottas.DotNetCore.WindowsService/StateMachines/ShutdownableServiceStateMachine.cs +++ b/Source/PeterKottas.DotNetCore.WindowsService/StateMachines/ShutdownableServiceStateMachine.cs @@ -1,16 +1,13 @@ using DasMulli.Win32.ServiceUtils; using PeterKottas.DotNetCore.WindowsService.Interfaces; -using System; -using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; -using System.Text; namespace PeterKottas.DotNetCore.WindowsService.StateMachines { public sealed class ShutdownableServiceStateMachine : IWin32ServiceStateMachine { - private readonly IShutdownableWin32Service serviceImplementation; - private ServiceStatusReportCallback statusReportCallback; + private readonly IShutdownableWin32Service _serviceImplementation; + private ServiceStatusReportCallback _statusReportCallback; /// /// Initializes a new to run the specified service. @@ -18,7 +15,7 @@ public sealed class ShutdownableServiceStateMachine : IWin32ServiceStateMachine /// The service implementation. public ShutdownableServiceStateMachine(IShutdownableWin32Service serviceImplementation) { - this.serviceImplementation = serviceImplementation; + _serviceImplementation = serviceImplementation; } /// @@ -31,11 +28,11 @@ public ShutdownableServiceStateMachine(IShutdownableWin32Service serviceImplemen [SuppressMessage("ReSharper", "ParameterHidesMember")] public void OnStart(string[] startupArguments, ServiceStatusReportCallback statusReportCallback) { - this.statusReportCallback = statusReportCallback; + _statusReportCallback = statusReportCallback; try { - serviceImplementation.Start(startupArguments, HandleServiceImplementationStoppedOnItsOwn); + _serviceImplementation.Start(startupArguments, HandleServiceImplementationStoppedOnItsOwn); statusReportCallback(ServiceState.Running, ServiceAcceptedControlCommandsFlags.Stop | ServiceAcceptedControlCommandsFlags.Shutdown, win32ExitCode: 0, waitHint: 0); } @@ -54,39 +51,39 @@ public void OnCommand(ServiceControlCommand command, uint commandSpecificEventTy { if (command == ServiceControlCommand.Stop) { - statusReportCallback(ServiceState.StopPending, ServiceAcceptedControlCommandsFlags.None, win32ExitCode: 0, waitHint: 3000); + _statusReportCallback(ServiceState.StopPending, ServiceAcceptedControlCommandsFlags.None, win32ExitCode: 0, waitHint: 3000); var win32ExitCode = 0; try { - serviceImplementation.Stop(); + _serviceImplementation.Stop(); } catch { win32ExitCode = -1; } - statusReportCallback(ServiceState.Stopped, ServiceAcceptedControlCommandsFlags.None, win32ExitCode, waitHint: 0); + _statusReportCallback(ServiceState.Stopped, ServiceAcceptedControlCommandsFlags.None, win32ExitCode, waitHint: 0); } else if (command == ServiceControlCommand.Shutdown) { try { - statusReportCallback(ServiceState.StopPending, ServiceAcceptedControlCommandsFlags.None, win32ExitCode: 0, waitHint: 3000); //this is probably too much, see note down below - serviceImplementation.Shutdown(); + _statusReportCallback(ServiceState.StopPending, ServiceAcceptedControlCommandsFlags.None, win32ExitCode: 0, waitHint: 3000); //this is probably too much, see note down below + _serviceImplementation.Shutdown(); } catch { } finally { - statusReportCallback(ServiceState.Stopped, ServiceAcceptedControlCommandsFlags.None, win32ExitCode: 0, waitHint: 0); + _statusReportCallback(ServiceState.Stopped, ServiceAcceptedControlCommandsFlags.None, win32ExitCode: 0, waitHint: 0); } } } private void HandleServiceImplementationStoppedOnItsOwn() { - statusReportCallback(ServiceState.Stopped, ServiceAcceptedControlCommandsFlags.None, win32ExitCode: 0, waitHint: 0); + _statusReportCallback(ServiceState.Stopped, ServiceAcceptedControlCommandsFlags.None, win32ExitCode: 0, waitHint: 0); } } } diff --git a/Source/Templates/PeterKottas.DotNetCore.WindowsService.MinimalTemplate/ExampleService.cs b/Source/Templates/PeterKottas.DotNetCore.WindowsService.MinimalTemplate/ExampleService.cs index 48d3f84..8f24516 100644 --- a/Source/Templates/PeterKottas.DotNetCore.WindowsService.MinimalTemplate/ExampleService.cs +++ b/Source/Templates/PeterKottas.DotNetCore.WindowsService.MinimalTemplate/ExampleService.cs @@ -1,41 +1,40 @@ using Microsoft.Extensions.PlatformAbstractions; using PeterKottas.DotNetCore.WindowsService.Interfaces; using System; -using System.Collections.Generic; using System.IO; -using System.Text; namespace PeterKottas.DotNetCore.WindowsService.MinimalTemplate { public class ExampleService : IMicroService { - private IMicroServiceController controller; + private readonly IMicroServiceController _controller; + private readonly string _fileName = Path.Combine(PlatformServices.Default.Application.ApplicationBasePath, "log.txt"); public ExampleService() { - controller = null; + _controller = null; } public ExampleService(IMicroServiceController controller) { - this.controller = controller; + _controller = controller; } - private string fileName = Path.Combine(PlatformServices.Default.Application.ApplicationBasePath, "log.txt"); public void Start() { Console.WriteLine("I started"); - Console.WriteLine(fileName); - File.AppendAllText(fileName, "Started\n"); - if (controller != null) + Console.WriteLine(_fileName); + File.AppendAllText(_fileName, "Started\n"); + + if (_controller != null) { - controller.Stop(); + _controller.Stop(); } } public void Stop() { - File.AppendAllText(fileName, "Stopped\n"); + File.AppendAllText(_fileName, "Stopped\n"); Console.WriteLine("I stopped"); } } diff --git a/Source/Templates/PeterKottas.DotNetCore.WindowsService.MinimalTemplate/PeterKottas.DotNetCore.WindowsService.MinimalTemplate.csproj b/Source/Templates/PeterKottas.DotNetCore.WindowsService.MinimalTemplate/PeterKottas.DotNetCore.WindowsService.MinimalTemplate.csproj index acd15a0..16b6e03 100644 --- a/Source/Templates/PeterKottas.DotNetCore.WindowsService.MinimalTemplate/PeterKottas.DotNetCore.WindowsService.MinimalTemplate.csproj +++ b/Source/Templates/PeterKottas.DotNetCore.WindowsService.MinimalTemplate/PeterKottas.DotNetCore.WindowsService.MinimalTemplate.csproj @@ -6,7 +6,7 @@ - + \ No newline at end of file diff --git a/Source/Templates/PeterKottas.DotNetCore.WindowsService.MinimalTemplate/Program.cs b/Source/Templates/PeterKottas.DotNetCore.WindowsService.MinimalTemplate/Program.cs index 177db18..0336e2c 100644 --- a/Source/Templates/PeterKottas.DotNetCore.WindowsService.MinimalTemplate/Program.cs +++ b/Source/Templates/PeterKottas.DotNetCore.WindowsService.MinimalTemplate/Program.cs @@ -1,5 +1,4 @@ using Microsoft.Extensions.PlatformAbstractions; -using PeterKottas.DotNetCore.WindowsService; using System; using System.IO; @@ -10,6 +9,7 @@ class Program public static void Main(string[] args) { var fileName = Path.Combine(PlatformServices.Default.Application.ApplicationBasePath, "log.txt"); + ServiceRunner.Run(config => { var name = config.GetDefaultName(); @@ -41,4 +41,4 @@ public static void Main(string[] args) }); } } -} \ No newline at end of file +} diff --git a/Source/Templates/PeterKottas.DotNetCore.WindowsService.StandardTemplate/ExampleService.cs b/Source/Templates/PeterKottas.DotNetCore.WindowsService.StandardTemplate/ExampleService.cs index 3088a75..d5a3dc0 100644 --- a/Source/Templates/PeterKottas.DotNetCore.WindowsService.StandardTemplate/ExampleService.cs +++ b/Source/Templates/PeterKottas.DotNetCore.WindowsService.StandardTemplate/ExampleService.cs @@ -1,18 +1,14 @@ using Microsoft.Extensions.Logging; -using Microsoft.Extensions.PlatformAbstractions; using PeterKottas.DotNetCore.WindowsService.Base; using PeterKottas.DotNetCore.WindowsService.Interfaces; using System; -using System.Collections.Generic; -using System.IO; -using System.Text; namespace PeterKottas.DotNetCore.WindowsService.StandardTemplate { public class ExampleService : MicroService, IMicroService { private IMicroServiceController _controller; - private ILogger _logger; + private readonly ILogger _logger; public ExampleService() { diff --git a/Source/Templates/PeterKottas.DotNetCore.WindowsService.StandardTemplate/LogFileProvider.cs b/Source/Templates/PeterKottas.DotNetCore.WindowsService.StandardTemplate/LogFileProvider.cs index 0b55e98..725f745 100644 --- a/Source/Templates/PeterKottas.DotNetCore.WindowsService.StandardTemplate/LogFileProvider.cs +++ b/Source/Templates/PeterKottas.DotNetCore.WindowsService.StandardTemplate/LogFileProvider.cs @@ -1,11 +1,11 @@ using Microsoft.Extensions.Logging; using System; -using System.Collections.Generic; using System.Text; namespace PeterKottas.DotNetCore.WindowsService.StandardTemplate { - // Thanks to Andrew Lock for basic details needed here: https://andrewlock.net/creating-a-rolling-file-logging-provider-for-asp-net-core-2-0/ + // Thanks to Andrew Lock for basic details needed here: + // https://andrewlock.net/creating-a-rolling-file-logging-provider-for-asp-net-core-2-0/ public class LogFileProvider : ILoggerProvider { public ILogger CreateLogger(string categoryName) @@ -26,13 +26,15 @@ public void AddMessage(DateTimeOffset timestamp, string message) public class FileLogger : ILogger { - LogFileProvider _provider; - string _category; + private readonly LogFileProvider _provider; + private readonly string _category; + public FileLogger(LogFileProvider provider, string categoryName) { _provider = provider; _category = categoryName; } + public IDisposable BeginScope(TState state) { return null; @@ -44,6 +46,7 @@ public bool IsEnabled(LogLevel logLevel) { return false; } + return true; } @@ -55,6 +58,7 @@ public void Log(DateTimeOffset timestamp, LogLevel logLevel, EventId eve } var builder = new StringBuilder(); + builder.Append(timestamp.ToString("yyyy-MM-dd HH:mm:ss.fff zzz")); builder.Append(" ["); builder.Append(logLevel.ToString()); diff --git a/Source/Templates/PeterKottas.DotNetCore.WindowsService.StandardTemplate/PeterKottas.DotNetCore.WindowsService.StandardTemplate.csproj b/Source/Templates/PeterKottas.DotNetCore.WindowsService.StandardTemplate/PeterKottas.DotNetCore.WindowsService.StandardTemplate.csproj index 277a887..aed535b 100644 --- a/Source/Templates/PeterKottas.DotNetCore.WindowsService.StandardTemplate/PeterKottas.DotNetCore.WindowsService.StandardTemplate.csproj +++ b/Source/Templates/PeterKottas.DotNetCore.WindowsService.StandardTemplate/PeterKottas.DotNetCore.WindowsService.StandardTemplate.csproj @@ -6,13 +6,13 @@ - - - - - + + + + + - + diff --git a/Source/Templates/PeterKottas.DotNetCore.WindowsService.StandardTemplate/Program.cs b/Source/Templates/PeterKottas.DotNetCore.WindowsService.StandardTemplate/Program.cs index 245542d..1d52803 100644 --- a/Source/Templates/PeterKottas.DotNetCore.WindowsService.StandardTemplate/Program.cs +++ b/Source/Templates/PeterKottas.DotNetCore.WindowsService.StandardTemplate/Program.cs @@ -1,10 +1,7 @@ -using System; -using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.Configuration; using Microsoft.Extensions.PlatformAbstractions; using Microsoft.Extensions.Logging; -using Microsoft.Extensions.FileProviders; using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.DependencyInjection.Extensions; namespace PeterKottas.DotNetCore.WindowsService.StandardTemplate { @@ -28,7 +25,7 @@ public static void Main(string[] args) .AddLogging(builder => { builder - .SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace) + .SetMinimumLevel(LogLevel.Trace) .AddProvider(new LogFileProvider()); // Implemented vanilla LogFile provider but is easily swapped for Nlog or SeriLog (et al.) providers }) @@ -37,12 +34,12 @@ public static void Main(string[] args) .AddConsole()) .BuildServiceProvider(); - var _logger = svcProvider.GetRequiredService().CreateLogger(); - + var logger = svcProvider.GetRequiredService().CreateLogger(); ServiceRunner.Run(config => { var name = config.GetDefaultName(); + config.Service(serviceConfig => { serviceConfig.ServiceFactory((extraArguments, controller) => @@ -52,19 +49,19 @@ public static void Main(string[] args) serviceConfig.OnStart((service, extraParams) => { - _logger.LogTrace("Service {0} started", name); + logger.LogTrace("Service {0} started", name); service.Start(); }); serviceConfig.OnStop(service => { - _logger.LogTrace("Service {0} stopped", name); + logger.LogTrace("Service {0} stopped", name); service.Stop(); }); serviceConfig.OnError(e => { - _logger.LogError(e, string.Format("Service {0} errored with exception", name)); + logger.LogError(e, string.Format("Service {0} errored with exception", name)); }); }); });