Use topshelf to create a Windows ServiceThis article briefly introduces another method for creating Windows Services.Create a. Net Windows Service in 5 steps with topshelfUse topshelf to create a Windows service.TopshelfIs an open-source cross-platform host service framework that supports windows and mono. You only need a few lines of code to build a convenient service host.
1. topshelf'sCodeHosted onHttp://topshelf-project.com/To download the latest code.
2. Create a console application using Visual StudioProgramReference the Assembly topshelf. dll in combination with log4net. dll.
3. Create a simple service class that contains two methods: Start and Stop. This service only demonstrates the code, so we output a log every five seconds.
Using System;
Using System. Timers;
Using Log4net;
NamespaceSamplewindowsservice
{
Public ClassSampleservice
{
PrivateTimer _ timer =Null;
ReadonlyIlog _ log = logmanager. getlogger (Typeof(Sampleservice ));
PublicSampleservice ()
{
DoubleInterval = 5000;
_ Timer =NewTimer (interval );
_ Timer. elapsed + =NewElapsedeventhandler (ontick );
}
Protected Virtual VoidOntick (ObjectSender, elapsedeventargs E)
{
_ Log. debug ("Tick :"+ Datetime. Now. tolongtimestring ());
}
Public VoidStart ()
{
_ Log. Info ("Sampleservice is started");
_ Timer. autoreset =True;
_ Timer. Enabled =True;
_ Timer. Start ();
}
Public VoidStop ()
{
_ Log. Info ("Sampleservice is stopped");
_ Timer. autoreset =False;
_ Timer. Enabled =False;
}
}
}4. Use topshelf to host our services in the main method. It mainly tells topshelf how to set the configuration of our services and call methods when starting and stopping services.
Using System. IO;
Using Log4net. config;
Using Topshelf;
NamespaceSamplewindowsservice
{
ClassProgram
{
Static VoidMain (String[] ARGs)
{
Xmlconfigurator. configureandwatch (
NewFileinfo (". \ Log4net. config"));
VaR host = hostfactory. New (x =>
{
X. enabledashboard ();
X. Service <sampleservice> (S =>
{
S. setservicename ("Sampleservice");
S. constructusing (name =>NewSampleservice ());
S. whenstarted (TC =>
{
Xmlconfigurator. configureandwatch (
NewFileinfo (". \ Log4net. config"));
TC. Start ();
});
S. whenstopped (TC => TC. Stop ());
});
X. runaslocalsystem ();
X. setdescription ("Sampleservice description");
X. setdisplayname ("Sampleservice");
X. setservicename ("Sampleservice");
});
Host. Run ();
}
}
}
4. Configure log4net and run our service. The service can be run as a console, which is very convenient during development. Easy to install servicesSamplewindowsservice.exe installAfter the installation is successful, you can start it on the service console or run the following command:Samplewindowsservice.exe startThe method for detaching a service is also very simple.Samplewindowsservice.exe uninstallRelatedArticle: Use topshelf to create a Windows Service
A WCF calculator in a Windows service with topshelf
WCF Service with topshelf using as a host, log4net as logging tool, and HTML as output