Topshelf
To get Topshelf up and running open up Visual Studio, start a Windows Console Project, and then use Nuget (if you don’t have Nuget installed, I suggest doing that ASAP, you’ll need it to follow along with any reference additions).
Once you have Topshelf and associated references added via Nuget create a new class file called StatusCheckIn and add the following code.
[sourcecode language=”csharp”]
using System;
using System.Timers;
namespace Sample.Services
{
public class StatusCheckIn
{
readonly Timer _timer;
public StatusCheckIn()
{
_timer = new Timer(5000) { AutoReset = true };
_timer.Elapsed += TimeHappened;
}
static void TimeHappened(object sender, EventArgs eventArgs)
{
Console.WriteLine("Status Time: {0} checking in.",
DateTime.Now);
Console.WriteLine("Sender Type: {0}",
sender.GetType());
Console.WriteLine("Event Argument Type: {0}",
eventArgs);
}
public void Start()
{
_timer.Start();
}
public void Stop()
{
_timer.Stop();
}
}
}
[/sourcecode]
After adding the StatusCheckIn Class, open up the Program.cs file and add or change the following code.
[sourcecode language=”csharp”]
using Topshelf;
namespace Sample.Services
{
class Program
{
static void Main()
{
HostFactory.Run(hostConfigurator =>
{
hostConfigurator.Service<StatusCheckIn>(
serviceConfigurator =>
{
serviceConfigurator.SetServiceName("TS");
serviceConfigurator.ConstructUsing(
name => new StatusCheckIn());
serviceConfigurator.WhenStarted(tc => tc.Start());
serviceConfigurator.WhenStopped(tc => tc.Stop());
});
hostConfigurator.RunAsLocalSystem();
hostConfigurator.SetDescription("Sample Host");
hostConfigurator.SetDisplayName("Display Name");
hostConfigurator.SetServiceName("Topshelf Service");
});
}
}
}
[/sourcecode]
If you run into an odd reference error, it is likely that VS2010 has determined you want the client profile of .NET 4.0 again. If anyone at MS on the VS2010/.NET 4.0 reads this, we DO NOT want this to be the default. It’s ridiculous that it gets set as default without some type of manual change. But I digress, open up the properties of the console/service project and set it under the dialog as shown.
NOTES: Working code available on Github under my Topshelf Repo.
