Create a topshelf service

First, create a console application

Now open nuget package manager console and run the following:

Install-Package log4net -Version 2.0.8

Install-Package Topshelf -Version 4.0.3

Install-Package Topshelf.Log4Net -Version 4.0.3

Create a startup class

public  static class Topshelf

{

private static readonly ILog log = LogManager.GetLogger(typeof(TopshelfService));

public static void Main()

{

 

var rc = HostFactory.Run(x =>

{

 

XmlConfigurator.Configure();

x.OnException((exception) =>

{

log.Error(log);

Console.WriteLine(“Exception thrown – ” + exception.Message);

});

 

x.Service<TopshelfService>(s =>

{

s.ConstructUsing(name => new TopshelfService());

s.WhenStarted((tc, hostControl) => tc.Start(hostControl));

s.WhenStopped((tc, hostControl) => tc.Stop(hostControl));

});

 

var runAsUser = ConfigurationManager.AppSettings[“RunAsUser”];

var runAsUserPwd = ConfigurationManager.AppSettings[“RunAsUserPassword”];

 

 

x.RunAs(runAsUser, runAsUserPwd);

 

 

 

x.SetDescription($”A simple service”);

x.SetDisplayName(“TopShelf demo service”);

x.SetServiceName(“Topshelf”);

 

 

});

 

var exitCode = (int)Convert.ChangeType(rc, rc.GetTypeCode());

Environment.ExitCode = exitCode;

}

}

Create a service class

    public class TopshelfService : ServiceControl

{

 

public bool Start(HostControl hostControl)

{

//Do stuff..

return true;

}

 

public bool Stop(HostControl hostControl)

{

 

//Do stuff..

return true;

}

}

}

Add log4net handler to your app.config

  <configSections>

<section name=”log4net” type=”log4net.Config.Log4NetConfigurationSectionHandler,     log4net” />

</configSections>

<log4net debug=”true”>

<root>

<level value=”DEBUG” />

<appender-ref ref=”RollingLogFileAppender” />

</root>

<appender name=”RollingLogFileAppender” type=”log4net.Appender.RollingFileAppender”>

<file value=”logs\logfile1.xml” />

<appendToFile value=”true” />

<rollingStyle value=”Size” />

<maxSizeRollBackups value=”20″ />

<maximumFileSize value=”10MB” />

<staticLogFileName value=”true” />

<layout type=”log4net.Layout.XmlLayout”>

<locationInfo value=”true” />

</layout>

</appender>

 

</log4net>

Also add user/pwd app settings

<appSettings>

<add key=”RunAsUser” value=”DOMROX01\PGI” />

<add key=”RunAsUserPassword” value=”pgiPa55″ />

</appSettings>

There you go!

Submit a Comment

Your email address will not be published. Required fields are marked *

Share This