Use the Topshelf component to build a simple Windows service.

Source: Internet
Author: User

Use the Topshelf component to build a simple Windows service.

I often discuss whether or not to understand the underlying principle of a component or language. In fact, I personally think that everyone has their own opinions on this issue and their personal circumstances are different, the selected method is different. I personally think that no matter what you learn, you should try to understand the corresponding principles and source code (don't worry about it here, let me finish it ). Understanding the underlying layer is not intended to allow you to write something similar and make it impossible for you to write it out. To rewrite one, you need to modify the entire underlying structure, you only need to understand the underlying knowledge so that you can select an appropriate method when writing business code, so that the underlying layer can work with the business layer to achieve the best efficiency. Any method is good or bad and requires a proper choice.

If you think that the above statements are incorrect or are inappropriate, you may not be able to forgive me because it is meaningless to argue that the right person will understand and think wrong. You can ignore them. There is no need to spend time and energy discussing such things.

The above is a nonsense. Let's start with the question below. The preceding section describes the Hangfire component used to set scheduled tasks and other operations. The Topshelf component is introduced here.

1. Overview of Topshelf Components

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

Creating a Windows service is similar to creating a console application. After creating a console application, you can create a single service class with the public Start and Stop methods. There are many service operations, such as automatic, automatic (Delay), manual and disabled startup options: local system, Local Service, Network Service, user name/password, or service creden。 prompted during installation. Service Startup dependencies, including SQL Server, MSMQ, and other multi-instance service installation service recovery options with different service names, including restarting, restarting, or running programs. Topshelf works with Mono to deploy services in Linux. Currently, the service installation function is only available for Windows.

Ii. Topshelf usage instructions

This section describes how to use the corresponding component background. Another method for using this component is in the HostFactory class. The following describes how to use this component.

1. configure a new service host

HostFactory. New (x => {// you can define services that do not require interface dependencies. This is only for the purpose of // not being used in this example. X. service <SampleSansInterfaceService> (s => {s. constructUsing () => 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 into logs.

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);            });          x.AddCommandLineSwitch("throwonstart", v => throwOnStart = v);          x.AddCommandLineSwitch("throwonstop", v => throwOnStop = v);          x.AddCommandLineSwitch("throwunhandled", v => throwUnhandled = v);          x.OnException((exception) =>          {            Console.WriteLine("Exception thrown - " + exception.Message);          });        });

3. Topshelf configuration Operation Method

3. Topshelf core Object Parsing

Take over the above and introduce the background and general operations. Here we will introduce some methods for a core object.

1. HostFactory. New ():

public static Host New(Action<HostConfigurator> configureCallback)    {      try      {        if (configureCallback == null)          throw new ArgumentNullException("configureCallback");        var configurator = new HostConfiguratorImpl();        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)        {          HostLogger.Get(typeof(HostFactory))               .InfoFormat("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. The method receives a parameter Action <HostConfigurator> configuration method call. This method returns the Host object, indicating that the Topshelf service Host is ready to run. ConfigureCallback. Method. DeclaringType; used to obtain the class that declares this member. DeclaringType. Namespace; used to obtain the Namespace of System. Type. ValidateConfigurationResult. CompileResults (configurator. Validate (); used to verify the configuration result.

2. HostFactory. Run ():

public static TopshelfExitCode Run(Action<HostConfigurator> configureCallback)    {      try      {        return New(configureCallback)          .Run();      }      catch (Exception ex)      {        HostLogger.Get(typeof(HostFactory))             .Error("The service terminated abnormally", ex);        HostLogger.Shutdown();                return TopshelfExitCode.AbnormalExit;      }    }

This method is a static method to configure and run a new service host, handle any exceptions and write them into logs. This method receives an Action <HostConfigurator> configureCallback configuration method call and returns the exit code of the Process returned by the main method of the application.

Iv. Summary

The above describes how to use the Topshelf component to create a simple Windows service. Here is just a simple introduction, not very in-depth introduction. If you need to know more, you can check the source code. After all, it is an open-source free component and a good component.

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

Related Article

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.