gpt4 book ai didi

c# - 使用 Topshelf 设置服务启动参数

转载 作者:行者123 更新时间:2023-11-30 14:27:24 25 4
gpt4 key购买 nike

我有一个服务有多个实例,每个实例都有不同的参数,目前我正在手动设置这些参数(准确地说是在另一个代码中)到注册表中服务的图像路径(例如 HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\MyService$i00)。所以我们的服务安装分两步完成。

我真的很想在 Topshelf 安装中合并这些步骤,例如

MyService.exe install -instance "i00" -config "C:\i00Config.json"

第一次尝试

我尝试了 TopShelf 的 AddCommandLineDefinition,但它似乎只在安装和通过控制台运行期间有效,而不是服务本身(不会向服务图像路径添加任何内容)。

第二次尝试

我试着看看是否可以使用 Topshelf 的 AfterInstall 来做到这一点,但没有任何运气。这是一个测试代码,看看它是否能正常工作(但不幸的是,Topshelf 在 AfterInstall 调用后覆盖了注册表)。

HostFactory.Run(x =>
{
x.UseNLog();
x.Service<MyService>(sc =>
{
sc.ConstructUsing(hs => new MyService(hs));
sc.WhenStarted((s, h) => s.Start(h));
sc.WhenStopped((s, h) => s.Stop(h));
});

x.AfterInstall(s =>
{
using (var system = Registry.LocalMachine.OpenSubKey("SYSTEM"))
using (var controlSet = system.OpenSubKey("CurrentControlSet"))
using (var services = controlSet.OpenSubKey("services"))
using (var service = services.OpenSubKey(string.IsNullOrEmpty(s.InstanceName)
? s.ServiceName
: s.ServiceName + "$" + s.InstanceName, true))
{

if (service == null)
return;

var imagePath = service.GetValue("ImagePath") as string;

if (string.IsNullOrEmpty(imagePath))
return;

var appendix = string.Format(" -{0} \"{1}\"", "config", "C:\i00config.json"); //only a test to see if it is possible at all or not
imagePath = imagePath + appendix;


service.SetValue("ImagePath", imagePath);
}
});

x.SetServiceName("MyService");
x.SetDisplayName("My Service");
x.SetDescription("My Service Sample");
x.StartAutomatically();
x.RunAsLocalSystem();
x.EnableServiceRecovery(r =>
{
r.OnCrashOnly();
r.RestartService(1); //first
r.RestartService(1); //second
r.RestartService(1); //subsequents
r.SetResetPeriod(0);
});
});

我找不到任何有关如何使用 TopShelf 完成此操作的相关信息,所以问题是,是否可以使用 TopShelf 来完成此操作?

最佳答案

好的,作为Travis提到,似乎没有针对此问题的内置功能或简单的解决方法。所以我基于自定义环境生成器为 Topshelf 编写了一个小扩展(大部分代码是从 Topshelf 项目本身借来的)。

我在 Github 上发布了代码,以防其他人发现它有用,这里是 Topshelf.StartParameters扩大。

基于扩展我的代码会是这样的:

HostFactory.Run(x =>
{
x.EnableStartParameters();
x.UseNLog();
x.Service<MyService>(sc =>
{
sc.ConstructUsing(hs => new MyService(hs));
sc.WhenStarted((s, h) => s.Start(h));
sc.WhenStopped((s, h) => s.Stop(h));
});

x.WithStartParameter("config",a =>{/*we can use parameter here*/});

x.SetServiceName("MyService");
x.SetDisplayName("My Service");
x.SetDescription("My Service Sample");
x.StartAutomatically();
x.RunAsLocalSystem();
x.EnableServiceRecovery(r =>
{
r.OnCrashOnly();
r.RestartService(1); //first
r.RestartService(1); //second
r.RestartService(1); //subsequents
r.SetResetPeriod(0);
});
});

我可以简单地设置它:

MyService.exe install -instance "i00" -config "C:\i00Config.json"

关于c# - 使用 Topshelf 设置服务启动参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32892760/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com