Friday, September 14, 2012

TopShelf–Framework for writing Windows Services

imageTopShelf is a .Net framework that makes it extremely simple to write Windows Services.

A simple example from their documentation shows just how easy it is to create a Windows Service from a Console based project:

 

public class TownCrier
{
    readonly Timer _timer;
    public TownCrier()
    {
        _timer = new Timer(1000) {AutoReset = true};
        _timer.Elapsed += (sender, eventArgs) => Console.WriteLine("It is {0} an all is well", DateTime.Now);
    }
    public void Start() { _timer.Start(); }
    public void Stop() { _timer.Stop(); }
}

public class Program
{
    public static void Main()
    {
        HostFactory.Run(x =>                                 
        {
            x.Service<TownCrier>(s =>                        
            {
               s.ConstructUsing(name=> new TownCrier());     
               s.WhenStarted(tc => tc.Start());              
               s.WhenStopped(tc => tc.Stop());               
            });
            x.RunAsLocalSystem();                            

            x.SetDescription("Sample Topshelf Host");        
            x.SetDisplayName("Stuff");                       
            x.SetServiceName("stuff");                       
        });                                                  
    }
}

No comments:

Post a Comment

Remember, if you want me to respond to your comment, then you need to use a Google/OpenID account to leave the comment.