Building a simple Windows service using the Topshelf component

Source: Internet
Author: User

Most of the time is to discuss the need to understand a component or a language of the underlying principle of the problem, in fact, I personally feel that for this problem, everyone has their own views, personal circumstances, the choice of the way will be different. I personally feel that no matter what to learn, should try to understand the corresponding principles and source code (here do not rush to spit groove, let me finish). The underlying understanding is not to let you write similar things, so that you can not write or write out, rewrite a need to modify the entire underlying structure, to understand the underlying knowledge is only to allow you to write business code, choose the right way, so that the bottom layer and the business layer to achieve the best efficiency. Either way there is bad and good and needs the right choice.

If you feel that the landlord above the wrong, or some inappropriate, but also hope that forgive me, because the argument of a point of no significance, think the person himself will understand, think wrong, can be ignored. There is no need to take the time and energy to discuss this kind of thing.

The above is a rip-off, cut to the chase. The previous section describes a component Hangfire, which is used to set up timed tasks and so on, and introduces another component topshelf.

I. Topshelf Components Overview

Topshelf is the Windows Service framework for the. NET platform. Topshelf can easily create Windows services, test services, debug services, and eventually install them into the Windows Service Control Manager (SCM). Topshelf by allowing developers to focus on the service logic rather than with the. The built-in services in the NET Framework support the details of the interaction. Developers do not need to understand the complex details of a service class, perform an installation through InstallUtil, or learn how to attach a debugger to a service for troubleshooting.

Create a Windows service similar to creating a console application, create a single service class with a public start and stop method after the console application is created. Services operate in many ways, automatic, automatic (delayed), manual and Disabled startup options for local system, local service, Network Service, username/password, or service credentials during installation prompts. Service startup dependencies include SQL SERVER,MSMQ and other multi-instance Service installation service recovery options with different service names, including restarting, rebooting, or running the program. Topshelf works with mono to deploy services to Linux. The service installation feature is currently limited to Windows.

Two. Topshelf Usage notes

After introducing the corresponding component background overview, here's how to use this component. The use of this component has another method, all in the Hostfactory class, the following specific introduction of a usage.

1. Configure a new service host

      Hostfactory.new (x + =                {                    // can define services that do not require interface dependencies, just to                    // shown in this example are not used.)                    x.service<samplesansinterfaceservice> (s = =new samplesansinterfaceservice ()); s. whenstarted (v = V.start ()); s.whenstopped (v = v.stop ());}); });

2. Configure and run a new service host, handle any exceptions and write them to the log

Hostfactory.run (x ={X.uselog4net ("Log4net.config"); X.useassemblyinfoforserviceinfo ();BOOL Throwonstart =False;BOOL Throwonstop =False;BOOL throwunhandled =False; X.service (settings =New Sampleservice (Throwonstart, Throwonstop, throwunhandled), S ={S.beforestartingservice (_ = = Console.WriteLine ("Beforestart")); S.beforestoppingservice (_ = Console.WriteLine ("Beforestop")); }); X.setstarttimeout (Timespan.fromseconds (10)); X.setstoptimeout (Timespan.fromseconds (10)); X.enableservicerecovery (R ={R.restartservice (3); R.runprogram (7,"Ping google.com"); R.restartcomputer (5,"Message"); R.oncrashonly (); R.setresetperiod (2 "throwonstart", V = throwonstart = V); X.addcommandlineswitch ( "throwonstop V); X.addcommandlineswitch ( "throwunhandled", V = throwunhandled = V); X.onexception ((Exception) => {Console.WriteLine ( " Span style= "COLOR: #800000" >exception thrown- "+ exception. Message); }); }); 

3.topshelf Configuration operation method

Three. Topshelf Core Object parsing

To undertake the above, the introduction of the relevant background and general operations, here to introduce a core object of some methods.

1.hostfactory.new ():

PublicStatic Host New (actionConfigurecallback) {Try{if (Configurecallback = =Null)ThrowNew ArgumentNullException ("Configurecallback");var configurator =NewHostconfiguratorimpl (); Type declaringtype =ConfigureCallback.Method.DeclaringType;if (declaringtype! =Null) {String defaultservicename =Declaringtype.namespace;if (!String. IsNullOrEmpty (defaultservicename)) configurator. Setservicename (Defaultservicename); } configurecallback (configurator); Configurator. Applycommandline (); Configurationresult result =Validateconfigurationresult.compileresults (configurator. Validate ());if (result. Message.length >0 Typeof "configuration result:\n{0}" , result. Message); } return Configurator. CreateHost (); } catch (Exception ex) {hostlogger.get (typeof (hostfactory)). Error ( "an exception occurred creating the Host ", ex); Hostlogger.shutdown (); throw       

This method is used to configure a new service host, which accepts a parameter action

2.hostfactory.run ():

 public static topshelfexitcode Run (action< Hostconfigurator> Configurecallback) {try< Span style= "COLOR: #000000" > {return New (Configurecallback). Run (); } catch (Exception ex) {hostlogger.get (typeof (hostfactory)). Error ( "the service terminated Abnormally" , ex); Hostlogger.shutdown (); return Topshelfexitcode.abnormalexit;}}    

The method is a static method that configures and runs the new service host, handles any exceptions, and writes them to the log. The method receives a parameter action

Four. Summary

The above is to introduce how to use the Topshelf component to create a simple Windows service method, here is just a simple introduction, not very deep introduction, if you need to know more things, you can see the source code, after all, is open source free components, is also a very good component.

Building a simple Windows service using the Topshelf component

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.