Introduction
For people that don't know what Topshelf is."Topshelf is a framework for hosting services written using the .NET framework.
The creation of services is simplified, allowing developers to create a simple console application that can be installed as a service using Topshelf.
The reason for this is simple: It is far easier to debug a console application than a service.
And once the application is tested and ready for production, Topshelf makes it easy to install the application as a service."
Source
This "Topshelf: Getting started guide" post will explain the basics and how to use Topshelf with:
Source code
You can find the source code of this post on: https://github.com/gergroen/Topshelf-getting-started-guidePost summary
Installing NuGet
First create a .Net core console project and install the next nuget packages.Create service class
Create a Service class. In this example the implementation has only log linesbut here you can add your own functionality for the windows service.
using Serilog; namespace Topshelf.GettingStarted { public class Service { public void Start() { Log.Information("Started"); } public void Stop() { Log.Information("Stopped"); } } }
Configure logging and windows service
Logging and the windows service are configured in the Program.Main.using System; using Serilog; namespace Topshelf.GettingStarted { class Program { static void Main(string[] args) { Log.Logger = new LoggerConfiguration() .WriteTo.Console() .WriteTo.File("log.txt", rollingInterval: RollingInterval.Day) .CreateLogger(); var rc = HostFactory.Run(x => { x.Service(s => { s.ConstructUsing(name => new Service()); s.WhenStarted(tc => tc.Start()); s.WhenStopped(tc => tc.Stop()); }); x.RunAsLocalSystem(); x.SetDescription("Topshelf Getting Started"); x.SetDisplayName("Topshelf.GettingStarted"); x.SetServiceName("Topshelf.GettingStarted"); x.UseSerilog(); }); var exitCode = (int)Convert.ChangeType(rc, rc.GetTypeCode()); Environment.ExitCode = exitCode; } } }
This is the result when we run the console application.
Control the windows service
To control the windows service we create the next batch files._install-service.bat
"%~dp0Topshelf.GettingStarted" install_start-service.bat
"%~dp0Topshelf.GettingStarted" start_stop-service.bat
"%~dp0Topshelf.GettingStarted" stop_uninstall-service.bat
"%~dp0Topshelf.GettingStarted" uninstallSet the "Copy to output directory" of the batch files to "Copy if newer".
The result
Now you can run _install-service.bat as Administrator to install the application as windows service.If you open the Services console you will see the application in the list.
Useful links:
Source codeTopshelf documentation
No comments:
Post a Comment