Getting Started
First, welcome to Topshelf! This page is all about getting started with using Topshelf.
Let’s start with a pretend ‘service’ that we want to be able to host in Microsoft Window’s Service Thing. For today our service will look like:
public class TownCrier
{
readonly Timer _timer;
public TownCrier()
{
_timer = new Timer(1000) {AutoReset = true};
_timer.Elapsed += (sender, eventArgs) => Console.WriteLine("It is {0} an all is well", DateTime.Now);
}
public void Start() { _timer.Start(); }
public void Stop() { _timer.Stop(); }
}
Ok, so there is our very simple service. Now lets host it. So lets create a ‘command line’ project in visual studio. And in the program.cs write the following.
HostFactory.Run(x => //1
{
x.Service<TownCrier>(s => //2
{
s.SetServiceName("tc"); //3
s.ConstructUsing(name=> new TownCrier()); //4
s.WhenStarted(tc => tc.Start()); //5
s.WhenStopped(tc => tc.Stop()); //6
});
x.RunAsLocalSystem(); //7
x.SetDescription("Sample Topshelf Host"); //8
x.SetDisplayName("Stuff"); //9
x.SetServiceName("stuff"); //10
}); //11
Now for the play by play:
- Here we are setting up the host using the HostFactory.Run the runner. We open up a new lambda where the ‘x’ in this case exposes all of the host level configuration. Using this approach the command arguments are extracted from environment variables.
- Here we are telling Topshelf that there is a service of type ‘TownCrier”. The lambda that gets opened here is exposing the service configuration options through the ‘s’ parameter.
- Here we can name the service if we want.
- This tells Topshelf how to build an instance of the service. Currently we are just going to ‘new it up’ but we could just as easily pull it from an IoC container with some code that would look something like ‘container.GetInstance<TownCrier>()’
- How does Topshelf start the service
- How does Topshelf stop the service
- Here we are setting up the ‘run as’ and have selected the ‘local system’
- We can also set up from the command line
- Interactively with a win from type prompt
- We can also just pass in some username/password as string arguments
- Here we are setting up the description for the winservice to be use in the windows service monitor
- Here we are setting up the display name for the winservice to be use in the windows service monitor
- Here we are setting up the service name for the winservice to be use in the windows service monitor
- Now that the lambda has closed, the configuration will be executed and the host will start running.