Running a Windows service from the console
Running a Windows service from a console is pretty straightforward, but I always forget the test for whether the exe is being run from a console or not. I know it contains ‘interactive’, but that’s not enough for Google to give me good results. Luckily, I remembered seeing this in RavenDB, so I just checked out the source in GitHub and voila!
But just for reference, here’s my basic shell for running a service from the console:
Program.cs:
1 using System;
2 using System.ServiceProcess;
3
4 namespace ServiceTest
5 {
6 static class Program
7 {
8 /// <summary>
9 /// The main entry point for the application.
10 /// </summary>
11 static void Main()
12 {
13 if (Environment.UserInteractive)
14 {
15 Console.WriteLine("Hit enter to exit");
16 var service = new Service1();
17 service.Start();
18 Console.ReadLine();
19 service.Stop();
20 }
21 else
22 {
23 ServiceBase[] ServicesToRun;
24 ServicesToRun = new ServiceBase[]
25 {
26 new Service1()
27 };
28 ServiceBase.Run(ServicesToRun);
29 }
30 }
31 }
32 }
Service1.cs:
1 using System.ServiceProcess;
2
3 namespace ServiceTest
4 {
5 public partial class Service1 : ServiceBase
6 {
7 public Service1()
8 {
9 InitializeComponent();
10 }
11
12 protected override void OnStart(string[] args)
13 {
14 Start();
15 }
16
17 protected override void OnStop()
18 {
19 Finish();
20 }
21
22 public void Start()
23 {
24 // Normal start stuff
25 }
26
27 public void Finish()
28 {
29 // Normal stop stuff
30 }
31 }
32 }