我已经制作了一个使用自定义参数的topshelf webservice:
string department = null;
// *********************Below is a TopShelf
HostFactory.Run(hostConfigurator =>
{
//Define new parameter
hostConfigurator.ApplyCommandLine();
//apply it
hostConfigurator.AddCommandLineDefinition("department", f => { department = f; });
Helpers.LogFile("xxx", "Got department:"+department);
hostConfigurator.Service<MyService>(serviceConfigurator =>
{
//what service we are using
serviceConfigurator.ConstructUsing(() => new MyService(department));
//what to run on start
serviceConfigurator.WhenStarted(myService => myService.Start());
// and on stop
serviceConfigurator.WhenStopped(myService => myService.Stop());
}
hostConfigurator.RunAsLocalService();
//****************Change those names for other
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)
。
当我使用&#34; -department:workshop&#34;进行调试时,一切正常。作为调试参数。但是当我试图将程序作为服务安装时
callforward.exe install -department:logistics
当我检查日志时,我确实创建了服务callforwardservice_logistics
,但参数还没有传递给MyService。
我做错了什么?
答案 0 :(得分:2)
默认情况下,Topshelf似乎不支持向服务启动配置添加自定义参数,安装后ImagePath
下的HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\MyService
值不包含其他参数-department:...
。您可以继承默认的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));
}
});
...
}
答案 1 :(得分:0)