Run a Windows Service as a console app

前端 未结 6 825
别跟我提以往
别跟我提以往 2020-12-02 12:30

I want to debug a Windows service but it pops an error message saying

Cannot start service from the command line or a debugger. A windows service

6条回答
  •  有刺的猬
    2020-12-02 13:10

    There is a nuget package made to solve this problem: install-package WindowsService.Gui

    What does the package do?

    It helps by creating a Play/Stop/Pause UI when running with a debugger attached, but also allows the windows service to be installed and run by the Windows Services environment as well. All this with one line of code! What is Service Helper Being someone who writes Windows Services a lot, it can be frustrating to deal with the headaches involved in debugging services. Often it involves tricks, hacks, and partial workarounds to test all of your code. There is no "just hit F5" experience for Windows Services developers.

    Service Helper solves this by triggering a UI to be shown if a debugger is attached that simulates (as closely as possible) the Windows Services Environment.

    The github project is here: https://github.com/wolfen351/windows-service-gui

    How to use?

    The easiest way to get Windows Service Helper in your project is to use the NuGet package ServiceProcess.Helpers on the NuGet official feed.

    Simply make a few changes to the typical code in the "Program.cs" for your application:

    using System.ServiceProcess;
    using ServiceProcess.Helpers; //HERE
    
    namespace DemoService
    {
        static class Program
        {
        static void Main()
        {
            ServiceBase[] ServicesToRun;
    
            ServicesToRun = new ServiceBase[] 
                { 
                    new Service1() 
                };
    
            //ServiceBase.Run(ServicesToRun);
            ServicesToRun.LoadServices(); //AND HERE
        }
        }
    }
    

    Disclosure: I'm the maintainer of this project

    Note: The UI is optional

提交回复
热议问题