views:

1936

answers:

3

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.

+16  A: 

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.

Jason Z
ServiceController implements IDisposable. Was not using the 'using' keyword or calling the Dispose method intentional?
Ken Browning
I agree it is always a good idea to dispose properly. In this instance, it only runs once. The OnCommitted fires after the installation program runs and then the service is managed like any other and automatically starts on the next reboot.
Jason Z
What about base.OnCommitted(...). Does that need to be called?
jm
A: 

thanks it run OK...
--------------C#---C#-----------------------
private System.ServiceProcess.ServiceInstaller serviceInstaller1;

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

+10  A: 

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.)

Andreas H.R. Nilsson