CustomWebHostService.cs 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. using Microsoft.AspNetCore.Hosting;
  2. using Microsoft.AspNetCore.Hosting.WindowsServices;
  3. using Microsoft.Extensions.DependencyInjection;
  4. using Microsoft.Extensions.Logging;
  5. using System.ComponentModel;
  6. using System.ServiceProcess;
  7. namespace QM.KJGH.CGGL
  8. {
  9. [DesignerCategory("Code")]
  10. internal class CustomWebHostService : WebHostService
  11. {
  12. private ILogger _logger;
  13. public CustomWebHostService(IWebHost host) : base(host)
  14. {
  15. _logger = host.Services
  16. .GetRequiredService<ILogger<CustomWebHostService>>();
  17. }
  18. protected override void OnStarting(string[] args)
  19. {
  20. _logger.LogInformation("OnStarting method called.");
  21. base.OnStarting(args);
  22. }
  23. protected override void OnStarted()
  24. {
  25. _logger.LogInformation("OnStarted method called.");
  26. base.OnStarted();
  27. }
  28. protected override void OnStopping()
  29. {
  30. _logger.LogInformation("OnStopping method called.");
  31. base.OnStopping();
  32. }
  33. }
  34. public static class WebHostServiceExtensions
  35. {
  36. public static void RunAsCustomService(this IWebHost host)
  37. {
  38. var webHostService = new CustomWebHostService(host);
  39. ServiceBase.Run(webHostService);
  40. }
  41. }
  42. }