How to pass arguments to windows service while service start using framework Topshelf

LAI TOCA
2 min readApr 22, 2019

--

Ref: topshelf-project.com

Topshelf is common wrapper that help us packaging our routine works to service. Passing argument(s) into application usually as means for programmer(s) to setup different behavior/branch of logic inside code section. If we want to apply the same way on Topshelf, we need to do some extra works on it.

Image that if we want to switch configuration by diverse environments (Debug/Qas/Release). And we might not having opportunity/permission to set environment variable nor writing extra information for doing this. Passing argument would be good choice for us to achieve it. See below code snippet:

In main entry method, we defined variable called: env. This variable will accept the argument that passing from program itself. Cause that Topshelf within predefined arguments for instance: install/uninstall…etc. So if we need customize arguments that not belong from list, we should defined and assigned it manually (See lien.43).

After added command line definition. We could passing “env” through this command line (supposed we used Debug as example):

XXXService.exe -env:Deubg

Now we could use variable: env to switch different configuration file from console mode but after we installed our service, the variable: env still remain blank/unset. Why?

After google and do a little research for the case, we found that Topshelf does not support passing argument(s) and bring them to stage of service start. So we need to do extra works for enable argument(s) passing through (See line.65).

The tricky was: save/overwrite our argument(s) information inside key ImagePath under services registry:

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\XXXService

Registry for services

Install service with <env> arugement and value as below example:

XXXService.exe install -env:Release

Then we are good to start our service with expected passing argument(s):)

Reference

--

--

LAI TOCA
LAI TOCA

Written by LAI TOCA

Coding for fun. (Either you are running for food or running for being food.)

Responses (1)