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?
views:
277answers:
2
+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
2009-07-17 10:20:58
+1, and my answer deleted :)
Patrick McDonald
2009-07-17 10:28:24
IIRC, you can also check Environment.UserInteractive, which is a lot cleaner than an argument. But I still use "-c" myself ;-p
Marc Gravell
2009-07-17 10:31:49
Looks really nice :) What is the best way to install it as service? Is there an easier way than the usual installer class?
Grzenio
2009-07-17 10:42:12
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
2009-07-17 10:45:22
+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
2009-07-17 10:35:32