skynyrd
9/12/2016 - 1:26 PM

Topshelf usage in C#

Topshelf usage in C#

// C#, Topshelf, NancyFX, Template

using System.Diagnostics;
using Topshelf;

namespace TopShelfIntro
{
    class Program
    {
        static void Main(string[] args)
        {
            RunAsWindowsService();
        }

        private static void RunAsWindowsService()
        {
            HostFactory.Run(config =>
            {
                config.Service<ServiceToStart>(selfHost =>
                {
                    selfHost.ConstructUsing(() => new ServiceToStart());
                    selfHost.WhenStarted(s => s.Start());
                    selfHost.WhenStopped(s => s.Stop());
                });
                config.RunAsLocalSystem();
                config.SetServiceName("ServiceName.Api");
                config.SetDisplayName("Service Display Name");
                config.SetDescription("Service Description");
            });
        }
    }
}

//Then you should build it in Relase mode, go to the artifact path using cmd
//with admin privileges, and then install the service "yourexefile.exe install"
public class ServiceToStart
{
    public ServiceToStart()
    {
    }

    public void Start()
    {
        Debug.WriteLine("Started");
    }

    public void Stop()
    {
        Debug.WriteLine("Stopped");
    }
}