views:

277

answers:

2

I would like to create an console exe application, that may be run as a standalone application as well as a windows service. Is it possible to do? What are actually the benefits of using svchost?

+11  A: 

Rewrite your windows service's main method like this, and it will be console application if you run with parametr -c, and yes don't forgot to change project type to console from project's property window

 public static void Main(string[] args)
 {
      Service service = new Service();
      if (args.Contains("-c", StringComparer.InvariantCultureIgnoreCase) || args.Contains("-console", StringComparer.InvariantCultureIgnoreCase))
      {
           service.StartService(args);
           Console.ReadLine();
           service.StopService();
           return;
      }
      ServiceBase[] ServicesToRun = new ServiceBase[] 
                                    { 
                                     service 
                                    };
      ServiceBase.Run(ServicesToRun);           
  }

StartService and StopService just call service's overrided OnStart, and OnStop methodes

ArsenMkrt
+1, and my answer deleted :)
Patrick McDonald
IIRC, you can also check Environment.UserInteractive, which is a lot cleaner than an argument. But I still use "-c" myself ;-p
Marc Gravell
Looks really nice :) What is the best way to install it as service? Is there an easier way than the usual installer class?
Grzenio
You should create installer by old ways, this code doesn't interrupt installer feature. to run as console you just need to create a bat file ;)
ArsenMkrt
+1  A: 

The best approach to this cases is to think about the notion of a component.

Your strategy should be develop a DLL with all the logic you need.

After that, you build a console application and windows service that use that DLL.

The notion of components and the possibility to reuse them is trivial and high advisable.

When you need to change your logic, you only must change the DLL, and replace with the old one. You don't need any kind of special deploy.

Ricardo