Search code examples
webwindows-servicesblazorexecutable

Host Blazor Consol app in Windows Service?


I got a Blazor .NET 5.0 website inside a console application project, how do I host this in a Windows Service?

I need a exe file for the sc.exe but do only get dll and a wwwwroot. Publishing the webpage does also not help.

Regards


Solution

  • Use Microsoft.Extensions.Hosting.WindowsServices nuget in your hosting project. You can create a generic host that can be run as a Windows Service by invoking 'UseWindowsService'.

    Example .NET Core 3.1/.Net 5:

    public class Program
    {
        public static void Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run();
        }
        
        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                })
                .UseWindowsService();
    }
    

    In .NET 6 project template for Blazor app hosted in ASP.NET Core it will be a bit different, because WebApplicationBuilder is used. IHostBuilder can be accessed with Host property.

    var builder = WebApplication.CreateBuilder(args);
    builder.Host.UseWindowsService();
    

    The service can be created using New-Service powershell command. You can read more here https://learn.microsoft.com/en-us/aspnet/core/host-and-deploy/windows-service?view=aspnetcore-6.0&tabs=visual-studio