TopShelf is an open source library that can be used to create services with .NET core projects. I am not sure though it is still being maintained, since the github source is now archived
To create a new service, you should first create a class that implements the "ServiceControl" interface - which is the Start and Stop methods..
To install the service, use the TopShelf API, specifically the HostFactory.
using System;
using Topshelf;
namespace MyService
{
class MyService : ServiceControl
{
public bool Start(HostControl hostControl)
{
// Add code to start the service here
Console.WriteLine("Service started");
return true;
}
public bool Stop(HostControl hostControl)
{
// Add code to stop the service here
Console.WriteLine("Service stopped");
return true;
}
}
class Program
{
static void Main(string[] args)
{
var service = HostFactory.New(x =>
{
x.Service<MyService>(s =>
{
s.ConstructUsing(name => new MyService());
s.WhenStarted(tc => tc.Start(null));
s.WhenStopped(tc => tc.Stop(null));
});
x.RunAsLocalSystem();
x.SetDescription("My Sample Service");
x.SetDisplayName("My Service");
x.SetServiceName("MyService");
});
service.Run();
}
}
}
Here is what we should do in order to run ASP.NET core project with TopShelf:
- Step 1: Install the following two packages: Microsoft.AspNetCore.Hosting.WindowsServices and Microsoft.Extensions.Hosting.WindowsServices
- Step 2: Add this to the service registration:
builder.Host.UseWindowsService();
- Step 3: Add this to configure the www root folder:
var builder = WebApplication.CreateBuilder(new WebApplicationOptions { ApplicationName = typeof(Program).Assembly.FullName, ContentRootPath = AppContext.BaseDirectory, WebRootPath = "wwwroot", Args = args });
- Step 4: Add this at the end. The MyService shouldn't do much.
if (args.Length > 0 && args[0] == "install") { HostFactory.New(x => { x.SetServiceName("MyService"); x.SetDisplayName("MyService Display Name"); x.SetDescription("My Service Description"); x.StartAutomatically(); x.RunAsLocalSystem(); x.Service<MyService>(); }).Run(); } else { app.Run(); }
- Step 5: Ensure to set the Kestrel web server settings properly: https://alexrait.blogspot.com/2022/12/configure-kestrel-in-net-core.html
- Step 6: Install the service by running
MyService.exe install