如何使Windows服务启动为"自动(延迟启动)"

Rob*_*son 24 c# wcf windows-services

场景:

作为Windows服务运行的WCF服务.帐户是"用户".


做了什么:

我已经覆盖了projectinstaller中的OnBeforeInstall,以便能够从配置文件中设置用户名和密码.


我能做什么:

我希望能够将starttype设置为Automatic(延迟启动)


我尝试过的:

我把以下的coderow放在重写的OnBeforeInstall中

serviceInstaller1.StartType = ServiceStartMode.Automatic + 1;

想象我会把ServiceStartMode枚举变成代表自动(延迟启动),不起作用.没有尝试任何更简单的因为我找不到任何尝试.


我在网上发现了什么:

我发现自动(延迟启动)将在.NET 4中可用,但这对我现在没有帮助. MSDN 我发现可以将DelayedAutoStart添加到服务的配置键中,但如果我应该从代码中执行此操作,这感觉就像是一个黑客攻击.但也许这是目前唯一可用的解决方案?

有任何想法吗?

罗伯特佩尔松,瑞典

fia*_*iat 39

现在,.NET 4.0就在这里:

serviceInstaller1.StartType = ServiceStartMode.Automatic;
serviceInstaller1.DelayedAutoStart = true;
Run Code Online (Sandbox Code Playgroud)

  • 我在我的ProjectInstaller.Designer.cs文件中有它以及凭据等. (3认同)

wj3*_*j32 5

你唯一的选择是使用的P/Invoke调用ChangeServiceConfig2SERVICE_CONFIG_DELAYED_AUTO_START_INFO.但由于您似乎不愿意添加注册表项,我怀疑您是否想要使用P/invoke.没有其他方法可以从.NET Framework(<4.0)中执行此操作.


jdk*_*ght 5

对于我的 .NET Framework 3.5 项目,我可以通过手动设置服务的值来将我的服务安装为“自动(延迟)”服务DelayedAutostart。例如:

public ProjectInstaller()
{
  ...

  AfterInstall += ProjectInstaller_AfterInstall;
}

void ProjectInstaller_AfterInstall(object sender, InstallEventArgs e)
{
  string serviceName = <YourSpecific>Installer.ServiceName;

  using (RegistryKey serviceKey = Registry.LocalMachine.OpenSubKey(@"System\CurrentControlSet\Services\" + serviceName, true))
  {
      serviceKey.SetValue("DelayedAutostart", 1, RegistryValueKind.DWord);
  }
}
Run Code Online (Sandbox Code Playgroud)

请注意,安装该服务后,直到计算机重新启动后,该服务才会列为“自动(延迟)” 。