Configure Multiple Windows Services in a Single Project

Asked

Viewed 116 times

1

I am developing a project like Windows Services and I came across the need to perform routines with different runtime and rules.

It is possible to have multiple windows services in a single project?

I tried the following code more unsuccessfully as in this way the exe always calls the first instantiated class:

ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[] {
  new ServiceEvento96(),
  new ServiceEvento17()
};

ServiceBase.Run(ServicesToRun);

1 answer

0

The solution to this case is very difficult to find, but I think I found it here, I’ll explain to you.

first - Create a class Installer, it should be public, not static, inherit from Installer and be decorated with the attribute RunInstaller parameter true.

[RunInstaller(true)]
public class MeuServicoInstaller : Installer
{
   public MeuServicoInstaller()
   {
     ServiceProcessInstaller processInstaller = new ServiceProcessInstaller();
     processInstaller.Account = ServiceAccount.LocalSystem;

     ServiceInstaller mainServiceInstaller = new ServiceInstaller();
     mainServiceInstaller.ServiceName = "Service1";
     mainServiceInstaller.Description = "Service One que faz tal coisa";
     mainServiceInstaller.ServicesDependedOn = new string [] { "Service2" };

     ServiceInstaller secondServiceInstaller = new ServiceInstaller();
     secondServiceInstaller.ServiceName = "Service2";
     secondServiceInstaller.Description = "Service Two que faz tal coisa";

     Installers.Add(processInstaller);
     Installers.Add(mainServiceInstaller);
     Installers.Add(secondaryServiceInstaller);
   }
}

In the constructor of this class you add your services the way the example shows, watch the line it contains ServicesDependedOn, there is saying that the serviço 1 depends on the serviço 2, so when the first is called, the second will also be because it is dependent.

2nd - This class you created will be invoked and instantiated when you run the process InstallUtil.exe.

Obs.: Attention as to the names of the services, they should be equal. I advise even to use the keyword nameof to maintain consistency of names instead of strings.

Examples:

mainServiceInstaller.ServiceName = nameof(Service1);

mainServiceInstaller.ServicesDependedOn = new string [] { nameof(Service2) };

Browser other questions tagged

You are not signed in. Login or sign up in order to post.