Topshelf – 基于自定义参数启动线程

我做了一个使用自定义参数的topshelf webservice:

string department = null; // *********************Below is a TopShelf code*****************************// HostFactory.Run(hostConfigurator => { hostConfigurator.AddCommandLineDefinition("department", f => { department = f; }); //Define new parameter hostConfigurator.ApplyCommandLine(); //apply it Helpers.LogFile("xxx", "Got department:"+department); hostConfigurator.Service(serviceConfigurator => { serviceConfigurator.ConstructUsing(() => new MyService(department)); //what service we are using serviceConfigurator.WhenStarted(myService => myService.Start()); //what to run on start serviceConfigurator.WhenStopped(myService => myService.Stop()); // and on stop } ); hostConfigurator.RunAsLocalService(); //****************Change those names for other services*******************************************// string d = "CallForwardService_" + department; hostConfigurator.SetDisplayName(d); hostConfigurator.SetDescription("CallForward using Topshelf"); hostConfigurator.SetServiceName(d); }); ... public class MyService string depTask; public MyService(string d) { //***********************Three tasks for three different destinations*********************** depTask = d; _taskL = new Task(Logistics); _taskP = new Task(Planners); _taskW = new Task(Workshop); Helpers.LogFile(depTask, "started working on threads for "+d); public void Start() { if (depTask == "logistics") { _taskL.Start(); Helpers.LogFile(depTask, "proper thread selected"); } ... 

Helpers.logfile只是写入文本文件。 您可以从上面的代码中看到参数department传递给MyService(string d) 。 当我使用调试时,一切正常,即“-department:workshop”作为调试参数。 但是,当我尝试使用callforward.exe install -department:logistics将程序作为服务callforward.exe install -department:logistics时,我在检查日志时创建了服务callforwardservice_logistics bu,该参数尚未传递给MyService。

我究竟做错了什么?

默认情况下,Topshelf似乎不支持向服务启动配置添加自定义参数,安装后HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\MyService下的ImagePath值不包含其他参数-department:... 您可以inheritance默认的WindowsHostEnvironment并重载Install方法,但我认为将以下代码添加到主机配置代码会更容易(可能更不好):

  // *********************Below is a TopShelf code*****************************// HostFactory.Run(hostConfigurator => { ... hc.AfterInstall(ihc => { using (RegistryKey system = Registry.LocalMachine.OpenSubKey("System")) using (RegistryKey currentControlSet = system.OpenSubKey("CurrentControlSet")) using (RegistryKey services = currentControlSet.OpenSubKey("Services")) using (RegistryKey service = services.OpenSubKey(ihc.ServiceName, true)) { const String v = "ImagePath"; var imagePath = (String)service.GetValue(v); service.SetValue(v, imagePath + String.Format(" -department \"{0}\"", department)); } }); ... }