Topshelf is a platform for deploying based on. NET Framework A Framework for developing services. It greatly simplifies service creation and deployment, and enables console applications to be deployed as services. Those of you who have developed Windows service programs should know that code debugging and service deployment are relatively troublesome. When I first contacted Topshelf, I found it so simple that I felt deeply sorry for the Windows service programs I wrote before…

Topshelf installation

Install Topshelf packages using Nuget.

Install-Package Topshelf
Copy the code

Topshelf configuration

The following is a gRPC service code that we deployed with Topshelf. The Topshelf key configuration is in the Main method. For more configuration, please read the official document.

Class Program {static void Main(string[] args) {// Configure and Run the host service hostFactory.run (x => {// specify the service type. CacheService <CacheService>(s => {// Build a service instance s.constructusing (name => new with new CacheService() CacheService()); // what should be done when the service is started? S.stopped (tc => tc.stop ())); }); // The service uses the local system account to run x.runaslocalSystem (); // Service description x. setDescription (" cache service "); // The service display name x.setDisplayName ("CacheService"); // Service name x.setServicename ("CacheService"); }); } } public class CacheService { private readonly string host = ConfigurationManager.AppSettings["Host"]; private readonly string port = ConfigurationManager.AppSettings["Port"]; readonly Server server; public CacheService() { server = new Server { Services = { MDCache.BindService(new CacheServiceImpl()) }, Ports = { new ServerPort(host, Convert.ToInt32(port), ServerCredentials.Insecure) } }; } public void Start() { server.Start(); } public void Stop() { server.ShutdownAsync(); }}Copy the code

Installation services

After ensuring that the assembly is successfully built, go to the bin\Debug directory, execute install and a Windows service is born. If you are prompted to start CMD as administrator, restart CMD as administrator.

xxx.exe install
Copy the code

Start the service

After the installation is successful, we can find it in Windows service and start it.

Note: because the serviceName must be unique, if we want to run multiple identical services on the same machine, we need to comment out the hard-coded serviceName and DisplayName Settings, and then specify the serviceName dynamically with command arguments.

// service display name // x.setDisplayName ("CacheService"); // Service name // x.setServicename ("CacheService");Copy the code

xxx.exe install -servicename cacheService
xxx.exe install -servicename cacheService1
Copy the code

Services to uninstall

Uninstall and start the same command, only need to change install to uninstall.

Reference links:

  • Topshelf
  • Topshelf-Github
  • Case Demo