我使用命令行参数将一些配置传递给Windows服务(它将是几个具有不同命令行的实例).
我的代码看起来像这样:
HostFactory.Run(x =>
{
x.Service<MyHost>(s =>
{
s.ConstructUsing(name => new MyHost());
s.WhenStarted(tc => tc.Start());
s.WhenStopped(tc => tc.Stop());
});
x.AddCommandLineDefinition("sqlserver", v => sqlInstance = v);
});
Run Code Online (Sandbox Code Playgroud)
当我安装服务时,我使用:
myhost.exe install -sqlserver:someinstance
Run Code Online (Sandbox Code Playgroud)
遗憾的是,sqlserver命令行选项仅在安装阶段可用,并且不会转到服务的参数.所以当我运行服务时,我没有得到我需要的参数值.
有没有办法修改TopShelf启动的服务命令行?
我有类似的要求,不幸的是,无法将命令行参数存储在文件中。
免责声明:此方法仅适用于 Windows
首先,我添加了安装后操作
x.AfterInstall(
installSettings =>
{
AddCommandLineParametersToStartupOptions(installSettings);
});
Run Code Online (Sandbox Code Playgroud)
我AddCommanLineParameterToStartupOptions更新了该服务的ImagePath Windows 注册表条目以包含命令行参数。
TopShelf 在此步骤之后添加其参数,以避免重复,servicename并且instance我将其过滤掉。您可能想要过滤掉的不仅仅是这些,但就我而言,这已经足够了。
private static void AddCommandLineParametersToStartupOptions(InstallHostSettings installSettings)
{
var serviceKey = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(
$"SYSTEM\\CurrentControlSet\\Services\\{installSettings.ServiceName}",
true);
if (serviceKey == null)
{
throw new Exception($"Could not locate Registry Key for service '{installSettings.ServiceName}'");
}
var arguments = Environment.GetCommandLineArgs();
string programName = null;
StringBuilder argumentsList = new StringBuilder();
for (int i = 0; i < arguments.Length; i++)
{
if (i == 0)
{
// program name is the first argument
programName = arguments[i];
}
else
{
// Remove these servicename and instance arguments as TopShelf adds them as well
// Remove install switch
if (arguments[i].StartsWith("-servicename", StringComparison.InvariantCultureIgnoreCase) |
arguments[i].StartsWith("-instance", StringComparison.InvariantCultureIgnoreCase) |
arguments[i].StartsWith("install", StringComparison.InvariantCultureIgnoreCase))
{
continue;
}
argumentsList.Append(" ");
argumentsList.Append(arguments[i]);
}
}
// Apply the arguments to the ImagePath value under the service Registry key
var imageName = $"\"{Environment.CurrentDirectory}\\{programName}\" {argumentsList.ToString()}";
serviceKey.SetValue("ImagePath", imageName, Microsoft.Win32.RegistryValueKind.String);
}
Run Code Online (Sandbox Code Playgroud)
此时你不能轻易做到这一点。我会在邮件列表上查看此主题
https://groups.google.com/d/msg/topshelf-discuss/Xu4XR6wGWxw/GFzmKdn_MeYJ
| 归档时间: |
|
| 查看次数: |
6946 次 |
| 最近记录: |