A while ago I blogged about a template project that I often use as my starting point for Windows services. I’ve recently been introduced to a component called TopShelf that makes writing a service even simpler as well as taking just about all the plumbing code needed for installing/uninstalling and running in debug mode.
Here’s an example of the code that goes into the Main method. It sets up the service, name, description, and you tell it what to call on the Start and Stop service control events.
Expand Code static void Main(string[] args)
{
const string name = "My Service Host";
const string description = "My Service Host Description";
var host = HostFactory.New(configuration =>
{
configuration.Service<ServiceHostControl>(
callback =>
{
callback.SetServiceName(name);
callback.ConstructUsing(s => new ServiceHostControl());
callback.WhenStarted(service => service.Start());
callback.WhenStopped(service => service.Stop());
});
configuration.SetDisplayName(name);
configuration.SetServiceName(name);
configuration.SetDescription(description);
configuration.DependsOnMsSql(); //Just here as an example of some of the features
configuration.RunAsLocalService();
});
host.Run();
}
I make reference in the code above to a class called ServiceHostControl. This class is the only other code I have in my template project as of now – it provides the stub methods for starting and stopping the service.
Expand Code
internal class ServiceHostControl
{
public void Start()
{
Console.WriteLine("starting...");
//Do everything here to start up the service...
Console.WriteLine("started.");
}
public void Stop()
{
Console.WriteLine("stopping...");
//Do everything here to shut the service down...
Console.WriteLine("stopped.");
}
}
There is no longer a need to have a service installer class anymore either in the project – all this functionality is brought to the party by the Topshelf component. To install your service, you simply drop to a command prompt and type in:
{serviceassembly.exe} install
and (as you can most likely guess) to uninstall, you type in:
{serviceassembly.exe} uninstall
It’s as simple as that.