Creating a Windows Service

After creating the project a Service class will be added to our project (we renamed it to MyWinService).

We can now open the designer for that class and add a Service Installer for our service by right-clicking and selecting the Add Installer option. A new ProjectInstaller class will be added to the project. We can configure it by opening the designer and setting the properties for its components (ServiceInstaller and ServiceProcessInstaller).

We can install the service using the installutil command from the VS Developer Command Prompt. To uninstall the service we can use the same command with the “/u” argument.

After the service has been installed we can start/stop it from the usual form we use to manage services. Once installed we don’t need to do any other operation. Of course before each rebuild we need to stop the service and restart it again after the rebuild has finished. We can’t rebuild while the service is running.

We can debug the process with the Attach To Process command from VS. Is often useful as well to write some log about what the process is doing. To do this we can use the EventLog object to write on the Windows Logs.

public partial class WinService : ServiceBase
    WindsorContainer container;
    IMyService service;
    public WinService()
        //Creates Castle Container
        container = new WindsorContainer();
        container.Install(new CastleInstaller());
    protected override void OnStart(string[] args)
        //Resolves MyService
        service = container.Resolve<IMyService>();
        service.Notify += (sender, message) =>
    protected override void OnStop()
        //Releases MyService

Debugging with a Console Application

To have a more easy debug a is good solution to create another project (e.g. a Console Application) that replicates the process’ logic. In this way we can use that application to debug and test our logic, instead of using Attach To Process/Windows Logs with the real process.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s