'Host ASP (.NET 6) in a Windows Service

I am currently hosting an ASP.NET (.NET 5) application in a Windows Service using WebHost and WebHostBuilder.

.NET 6 introduced WebApplication and WebApplicationBuilder. How can I use these to host in a Windows Service?



Solution 1:[1]

You would use the UseWindowsService() extension method documented here:

https://docs.microsoft.com/en-us/aspnet/core/host-and-deploy/windows-service?view=aspnetcore-6.0&tabs=visual-studio#app-configuration

As is the case in previous versions, you need to install the Microsoft.Extensions.Hosting.WindowsServices NuGet package.

Implementing this in .NET 6 with WebApplicationBuilder requires a workaround:

var webApplicationOptions = new WebApplicationOptions() { ContentRootPath = AppContext.BaseDirectory, Args = args, ApplicationName = System.Diagnostics.Process.GetCurrentProcess().ProcessName };
var builder = WebApplication.CreateBuilder(webApplicationOptions);

builder.Host.UseWindowsService();

Updated:

Microsoft has changed how services should be created as the fix for this. The --contentRoot argument should be used with the exe.

sc config MyWebAppServiceTest binPath= "$pwd\WebApplication560.exe --contentRoot $pwd\"
New-Service -Name {SERVICE NAME} -BinaryPathName "{EXE FILE PATH} --contentRoot {EXE FOLDER PATH}" -Credential "{DOMAIN OR COMPUTER NAME\USER}" -Description "{DESCRIPTION}" -DisplayName "{DISPLAY NAME}" -StartupType Automatic

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Josh Close