What is the accepted pattern for an application that can be run as a service or as a console application

前端 未结 4 866
半阙折子戏
半阙折子戏 2021-02-06 16:43

I have a project that is deployed to production as a windows service. However for local development purposes it would be useful to run it as a console application. At the moment

4条回答
  •  旧巷少年郎
    2021-02-06 17:16

    I suspect your test project was configured as a windows exe, not a console exe. With a windows exe Console.ReadLine will return immediately.

    To have a console exe that works both as a service and at the command line, start it as a service project (in Visual Studio) - and add a check on Environment.UserInteractive - i.e.

    static void Main() {
        if(Environment.UserInteractive) {
            // code that starts the listener and waits on ReadLine
        } else {
            // run the service code that the VS template injected
        }
    }
    

    You can of course also use a command line switch. I have example on microsoft.public.dotnet.languages.csharp that acts as:

    • an installer / uninstaller
    • a service
    • a console-mode app

    depending on the switches

提交回复
热议问题