Creating a Windows Service itself is a hassle that includes various aspects of it such as configuration, install-uninstall, recovery, start mode and so on. Managing this setting either can be done manually or by writing many batch/command files that help in deployment and management of Windows Services.

Recently, I came across an ultimate .NET OSS library that provides control of nearly everything related to a Windows Service. The library is known as “TOPSHELF”, the contribution credit for this library goes to Travis Smith, Charles Patterson and a few more awesome contributors. See the well-managed documentation of this project here.

How does this library tool make a difference creating a Windows Service? Let's try to create a Windows Service as in the following:

publicclass TownCrier

{

readonly Timer _timer;

public TownCrier()

{

_timer = new Timer(1000)

{

AutoReset = true

};

_timer.Elapsed += (sender, eventArgs) = > Console.WriteLine(

"It is {0} and all is well", DateTime.Now);

}

publicvoid Start()

{

_timer.Start();

}

publicvoid Stop()

{

_timer.Stop();

}

}

The preceding code is expected to run as a Windows Service. Now conventionally, to make it a Windows Service, one must add a Windows Service file type, then WindowsInstaller and so on. Rather I'll be using the Topshelf library for a hassle-free setup.

Windows Services made easy

publicclass Program

{

publicstaticvoid Main()

{

HostFactory.Run(x = > //1

{

x.Service < TownCrier > (s = > //2

{

s.ConstructUsing(name = > new TownCrier()); //3

s.WhenStarted(tc = > tc.Start()); //4

s.WhenStopped(tc = > tc.Stop()); //5

});

x.RunAsLocalSystem(); //6

x.SetDescription("Sample Topshelf Host"); //7

x.SetDisplayName("Stuff"); //8

x.SetServiceName("Stuff"); //9

}); //10

}

}

That's it. Now when I run this code my service will run as a console application. Without Topshelf I would have created a separate class to run the service as a console application. But now I can do it in a few lines of code and that is quite awesome. Let's simply press F5 in Visual Studio to run the preceding code.

Running as Console service

Let's simply press F5 in Visual Studio to run the preceding code.

Installation of Windows Service

Simply call the generated .exe file with an argument.

SampleService.exe install

You will see some success log output on the command prompt:

Let's have a look at the Services window. Go to Run, then Services.msc.

And I can see my service has begun and is running. How cool, isn't it? I'm sure this kinda stuff will make the DevOPs guys happy. There are many configuration options that make use of this library easy. I can say that the OOS stack of .NET is coming into the picture and helping developers making software better and better everyday.