← Back to blog
.NET
07 December 2016 · 7 min read

Adding Custom Arguments to Topshelf

Topshelf is an amazing framework that let you easily host and build Windows services.

Topshelf is really extensible, but recently I struggled to find how to configure a custom argument to the service.

This post is simple tip to help you create custom arguments to a Topshelf service and use it in the command line.

This can be accomplished simply using the Host Configurations.

If you use the method "AddCommandLineDefinition" you will be able to specify the name of your argument (case sensitive) and how you want to use it.

You can find here a simple example.

using System;
using System.IO;
using System.Timers;
using Topshelf;
namespace TopShelfCustomArgs
{
public class FolderProcessor
{
readonly Timer _timer;
public FolderProcessor(string path, int frequency)
{
_timer = new Timer(frequency * 1000) { AutoReset = true };
_timer.Elapsed += (sender, eventArgs) =>
{
string[] fileEntries = Directory.GetFiles(path);
foreach (var fileEntry in fileEntries)
Console.WriteLine($"At {DateTime.Now}: {fileEntry}");
};
}
public void Start() { _timer.Start(); }
public void Stop() { _timer.Stop(); }
}
public class Program
{
public static void Main()
{
string path = string.Empty;
int frequency = 10;
HostFactory.Run(x =>
{
x.Service<FolderProcessor>(s =>
{
s.ConstructUsing(name => new FolderProcessor(path, frequency));
s.WhenStarted(tc => tc.Start());
s.WhenStopped(tc => tc.Stop());
});
x.RunAsLocalSystem();
x.SetDescription("Topshelf Host");
x.SetDisplayName("Folder Processor");
x.SetServiceName("Folder Processor");
x.AddCommandLineDefinition("path", v => path = v);
x.AddCommandLineDefinition("frequency", v => frequency = Int32.Parse(v));
});
}
}
}
view raw Program.cs hosted with ❤ by GitHub

Then you can execute your service sending your argument as you can see in the following example (command line invoke).

	.\TopShelfCustomArgs.exe run -path:"c:\temp" -frequency:2

Hope this helps.

Developer Insights

What I'm building, learning, and discovering each week.

By signing up, you'll get my free weekly newsletter plus occasional updates about my courses. You can unsubscribe anytime.