Skip to content

Tutorial

Mike Schenk edited this page May 5, 2016 · 4 revisions

Using Visual Studio

  1. Create a Console Application.

.NET 3.5 and above is supported

  1. Install the EasyServiceHost package

Use Package Manager Console or

Install-Package EasyServiceHost
  1. Change Main to return int
namespace Tutorial
{
	class Program
	{
		static int Main(string[] args)
		{
		}
	}
}
  1. Create a bootstrap class

This class will become the entry point to your service.

The class can be named anything. It must have a public default (no-argument) constructor. It must implement the IManagedService interface:

	class Bootstrap : IManagedService
	{
		public void Start(IServiceHost host)
		{
			//TODO: start a new thread or other asynchronous process to do the work of your service.
		}

		public void Stop(TimeSpan timeLimit)
		{
			//TODO: stop the thread or asynchronous process within the time specified in timeLimit.
		}
	}

The constructor and the Start method both run while the Windows Service Control Manager is waiting for a response to the start command. If you have initialization that could take longer than a couple of seconds, you should start a new thread to run it.

  1. Call ManagedHost.RunOne(args) from Main
		static int Main(string[] args)
		{
			return ManagedHost.RunOne(args);
		}

This will handle and installation, uninstallation, and running your service depending on the command-line arguments supplied.

  1. Add configuration sections to App.config
<configuration>
	<configSections>
		<section name="WindowsServiceSettings" type="EasyServiceHost.WindowsServiceSettings, EasyServiceHost" />
		<section name="ManagedServiceSettings" type="EasyServiceHost.ManagedServiceSettings, EasyServiceHost" />
	</configSections>

	<WindowsServiceSettings ServiceName="Tutorial" DisplayName="Easy Service Host Tutorial" />
	<ManagedServiceSettings BootstrapClass="Tutorial.Bootstrap, Tutorial" />
</configuration>
  1. Make your service do something

  2. Run your project Just start the service from Visual Studio, or run the .exe. You will see a command window with your service running.

  3. Install your service

Tutorial.exe -install

Notice that you were presented with a UAC prompt to elevate if necessary.

Notice the Tutorial.exe.installed file was created in the directory where your .exe is.

Go look at your services and see that it is running.

  1. Uninstall your service
Tutorial.exe -uninstall

This will first stop the service and then uninstall it.

  1. Install another copy of your service

  2. Uninstall the other copy of your service

Clone this wiki locally