How to automatically start your service after install?

Viewed 28342

How do you automatically start a service after running an install from a Visual Studio Setup Project?

I just figured this one out and thought I would share the answer for the general good. Answer to follow. I am open to other and better ways of doing this.

7 Answers

Add the following class to your project.

using System.ServiceProcess;  

class ServInstaller : ServiceInstaller
{
    protected override void OnCommitted(System.Collections.IDictionary savedState)
    {
        ServiceController sc = new ServiceController("YourServiceNameGoesHere");
        sc.Start();
    }
}

The Setup Project will pick up the class and run your service after the installer finishes.

Small addition to accepted answer:

You can also fetch the service name like this - avoiding any problems if service name is changed in the future:

protected override void OnCommitted(System.Collections.IDictionary savedState)
{
    new ServiceController(serviceInstaller1.ServiceName).Start();
}

(Every Installer has a ServiceProcessInstaller and a ServiceInstaller. Here the ServiceInstaller is called serviceInstaller1.)

thanks it run OK...

private System.ServiceProcess.ServiceInstaller serviceInstaller1;

private void serviceInstaller1_AfterInstall(object sender, InstallEventArgs e)
{
    ServiceController sc = new ServiceController("YourServiceName");
    sc.Start();
}

There is also another way which does not involve code. You can use the Service Control Table. Edit the generated msi file with orca.exe, and add an entry to the ServiceControl Table.

Only the ServiceControl, Name,Event and Component_ columns are mandatory. The Component_ column contains the ComponentId from the File Table. (Select the File in the file table, and copy the Component_value to the ServiceControl table.)

The last step is to update the value of StartServices to 6575 in table InstallExecutesequence. This is sufficient to start the service.

By the way, the service install table allows you to configure the installer to install the windows service.

Related