BattlefieldDuck

Blazor Server as a Windows Service

Blazor Server as a Windows Service is very easy, but there are not many articles talking about this, so I decided to write this.

Install NuGet Package

Install Microsoft.Extensions.Hosting.WindowsServices from NuGet Package Manager.

Edit Program.cs

Add using Microsoft.Extensions.Hosting.WindowsServices;.

using Microsoft.Extensions.Hosting.WindowsServices;

Change var builder = WebApplication.CreateBuilder(args); to the following code. ContentRootPath is required for Windows Service, otherwise the service will fail to the start.

var builder = WebApplication.CreateBuilder(new WebApplicationOptions()
{
    ContentRootPath = WindowsServiceHelpers.IsWindowsService() ? AppContext.BaseDirectory : default,
    Args = args
});

Add this before var app = builder.Build();.

builder.Host.UseWindowsService();

Publish the app

Publish your app and click Open folder and grab your program exe path.

Create and start the Windows Service

Run cmd.exe as administrator.

Create a Service with the following command. The <BIN_PATH> should be your program exe path.

sc create <SERVICE_NAME> binPath="<BIN_PATH>"

Example,

sc create WindowsGSM binPath="D:\WindowsGSM\WindowsGSM\bin\Release\net6.0\publish\WindowsGSM.exe"

Start the Service with the following command.

net start <SERVICE_NAME>

Example,

net start WindowsGSM

Your app should be now started as Windows Service. 👏
If your service fail to start, you may run Event Viewer program on Windows to see the service log. Good luck!

本作品采用 知识共享署名-非商业性使用-禁止演绎 4.0 国际许可协议 进行许可。