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

前端 未结 4 860
半阙折子戏
半阙折子戏 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:15

    I have done this before by implementing a normal Windows Service (by deriving from ServiceBase), but putting a check in the main method to check for a command line argument.

    If the args contain /console, start the console version, otherwise start the service.

    Something like this:

    internal class MyService : ServiceBase
    {
        internal static void Main(string[] args)
        {
            if (args.Length == 0)
            {
                // run as a service....
                ServiceBase[] servicesToRun = new ServiceBase[] {new MyService()};
                Run(servicesToRun);
            }
            else
            {
                // run as a console application....
            }
        }
    }
    

提交回复
热议问题