Sunday, August 11, 2013

Creating and Installing Windows Services with TopShelf


TopShelf  is a library for .NET that makes it very easy to create and install a Windows service.

For example, all necessary code for creating Windows Service might look like:
 static void Main()  
 {  
   HostFactory.Run(x =>  
   {  
     x.UseLog4Net("log4net.config");  
     x.Service(s =>   
      {  
        s.ConstructUsing(name => new MyService());  
        s.WhenStarted(tc => tc.OnStart());  
        s.WhenStopped(tc => tc.OnStop());  
      });  
     x.SetDescription("My Service is Great!");  
     x.SetDisplayName("My Service");  
     x.SetServiceName("MyService");  
     x.RunAsLocalSystem();  
  });  
 }  

MyService is a class with two public methods(OnStart and OnStop). OnStart contains code to preform in service. OnStop may do some cleanup.

The best benefit that comes with TopShelf is that service is started as Console application during development(running, debugging etc).
But if you want to install service as real Windows Service, you just need to run you exe file with special parameter:
 MyService.exe install