我的服务可执行文件中有两个类似的Windows服务。共享配置文件中某个设置的值确定是安装Windows服务还是只安装一个。
在共享配置文件中,有一个名为Enabled
的设置。如果设置为true,则应安装两个Windows服务。如果将其设置为false,则只应安装第一个Windows服务。
我的项目安装程序使用条件来检查安装时的Enabled
设置,它似乎运行良好...因为我只看到第一个Windows服务,当它设置为false并且看到两者当它被设置为真时。
并且,如果Enabled
设置设置为true并且安装了两个Windows服务,那么当我启动它们时它们似乎都运行良好。但是,当Enabled
设置设置为false且仅安装了第一个Windows服务时,我无法启动第一个(也是唯一的)Windows服务。
这是我收到的错误消息:
Windows could not start the Service1 service on Local Computer.
Error 1053: The service did not respond to the start or control request in a timely fashion.
这是我的ProjectInstaller:
[RunInstaller(true)]
public partial class ProjectInstaller : Installer
{
private ServiceProcessInstaller serviceProcessInstaller1;
private ServiceInstaller serviceInstaller1;
private ServiceInstaller serviceInstaller2;
public ProjectInstaller()
{
this.InitializeComponent();
}
}
这是ProjectInstaller.Designer中的InitializeComponent()方法:
private void InitializeComponent()
{
Assembly service = Assembly.GetAssembly(typeof(ProjectInstaller));
Configuration config = ConfigurationManager.OpenExeConfiguration(service.Location);
Installer[] installerArray = null;
InstallerCollection installers = base.Installers;
components = new System.ComponentModel.Container();
this.serviceProcessInstaller1 = new ServiceProcessInstaller();
this.serviceInstaller1 = new ServiceInstaller();
this.serviceInstaller2 = null;
this.serviceProcessInstaller1.Account = ServiceAccount.LocalSystem;
this.serviceProcessInstaller1.Password = null;
this.serviceProcessInstaller1.Username = null;
this.serviceInstaller1.DisplayName = "Service1";
this.serviceInstaller1.ServiceName = "Service1";
if (config.AppSettings.Settings["Enable"].Value.Equals("true"))
{
this.serviceInstaller2 = new ServiceInstaller();
this.serviceInstaller2.DisplayName = "Service2";
this.serviceInstaller2.ServiceName = "Service2";
installerArray = new Installer[] { this.serviceProcessInstaller1, this.serviceInstaller1, this.serviceInstaller2 };
}
else
{
installerArray = new Installer[] { this.serviceProcessInstaller1, this.serviceInstaller1 };
}
installers.AddRange(installerArray);
}
以下是Program:
中的代码static void Main()
{
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new Service1(),
new Service2()
};
ServiceBase.Run(ServicesToRun);
}
问题似乎出现在ServiceBase中,因为有两个服务正在运行,但我不知道如果第二个服务没有安装,如何只启动第一个服务。
我认为我可以检查服务是否已安装,并将Program中的代码更改为以下内容,但仍然收到错误:
static void Main()
{
ServiceBase[] ServicesToRun;
ServiceController serviceController = ServiceController.GetServices().FirstOrDefault(s => s.ServiceName == "Service2");
if (serviceController != null)
{
ServicesToRun = new ServiceBase[]
{
new Service1(),
new Service2()
};
}
else
{
ServicesToRun = new ServiceBase[]
{
new Service1()
};
}
ServiceBase.Run(ServicesToRun);
}
感谢。