Creating windows service using Topshelf
Hi,
I am creating windows services using Topshelf for a while and I forget how “hard” (not that hard but harder) it was to create a windows service without Topshelf.
Topshelf is a lightweight framework for building Windows services using the .NET framework. The idea is to create a console application and “publishing” it as a service with command line. No more dedicated window service project and an installer.
So, how does it work? here is a simple example:
1. Create new “console application”
2. Create your service class
public class MyService : IService
{
public void Start()
{
Console.WriteLine("Running...");
}
public void Stop()
{
Console.WriteLine("Done!");
}
}
3. write something like the code below: (here we are using topshelf)
static void Main(string[] args)
{
RunConfiguration cfg = RunnerConfigurator.New(x =>
{
x.ConfigureService<MyService>(s =>
{
s.Named("MySampleService");
s.HowToBuildService(service => new MyService());
s.WhenStarted(service => service.Start());
s.WhenStopped(service => service.Stop());
});
x.RunAsLocalSystem();
x.SetDescription("Sample Topshelf Host");
x.SetDisplayName("The service");
x.SetServiceName("MySampleService");
});
Runner.Host(cfg, args);
}
That’s it!
now you have a console application that will run the Start() method when you start it and run the Stop() method when you stop it. Very comfortable when you are in the development process and you want to run or debug your service.
Now to install it or uninstall run the command line:
myservice.exe install
myservice.exe uninstall
Enjoy your new service, I personally wrapped Topshelf that I wont need to copy the code above every time:
I created an interface called IService
public interface IService
{
void Start();
void Stop();
}
And a simple method called ServiceCreator
public static void ServiceCreator<T>(string name, string displayName, string description, string[] args) where T : IService, new()
{
RunConfiguration cfg = RunnerConfigurator.New(x =>
{
x.ConfigureService<MyService>(s =>
{
s.Named(name);
s.HowToBuildService(service => new T());
s.WhenStarted(service => service.Start());
s.WhenStopped(service => service.Stop());
});
x.RunAsLocalSystem();
x.SetDescription(description);
x.SetDisplayName(displayName);
x.SetServiceName(name);
});
Runner.Host(cfg, args);
}
Now my main looks like this:
static void Main(string[] args)
{
ServiceCreator<MyService>("Name", "Display Name", "desciption", args);
}
Hope it will help you to create and debug windows services
Update: MAY-2012
The API has changed a bit, now in order to install the server you need to run "{your_exe} install" and to uninstall "{your_exe} uninstall"
Keep Writing, Compiling, and Debugging
Alon Nativ