Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET Core 6 app not able to find UseWindowsService

My objective is to run an ASP.NET Core 6 app as Windows service in the simplest way, which I understood to use the code shown below.

I have included both of these lines (though only the top should be necessary):

using Microsoft.AspNetCore.Hosting.WindowsServices;
using Microsoft.Extensions.Hosting.WindowsServices;

and installed the nuget packages:

<PackageReference Include="Microsoft.Extensions.Hosting.WindowsServices" Version="6.0.0" />
<PackageReference Include="Microsoft.AspNetCore.Hosting.WindowsServices" Version="6.0.0" />

But this code cannot resolve .UseWindowsService() when using IWebHostBuilder:

    public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseConfiguration(Configuration)
            .ConfigureServices(ConfigureServices)
            .UseUrls(Configuration.GetBindHostUrl())
            .UseStartup<Startup>()
            .UseWindowsService();   // not found

The error I get is:

'IWebHostBuilder' does not contain a definition for 'UseWindowsService' and the best extension method overload 'WindowsServiceLifetimeHostBuilderExtensions.UseWindowsService(IHostBuilder)' requires a receiver of type 'IHostBuilder'

What am I missing here?

like image 621
James Harcourt Avatar asked Jan 26 '26 15:01

James Harcourt


2 Answers

Instead of using the WebHost, you could try to use the more generic IHostBuilder:

 var host = Host.CreateDefaultBuilder(args)
                .UseWindowsService()
                .UseSystemd()
                .ConfigureWebHostDefaults(webbuilder =>
                {
                    //Configure here your WebHost. For example Startup;
                    webbuilder.UseStartup<Startup>();
            });

Edit:
Moved from the comments, because multiple people found it useful and to improve the visibility of the comment:
To use the UseWindowsService() method, you need to install the WindowsServices NuGet-Package. In some cases, it will build without the NuGet-Package, but it will fail to run!

like image 174
TheTanic Avatar answered Jan 28 '26 04:01

TheTanic


I just migrated from .net 3 to latest 7.0 and VS2019 to 2022, then had to install dependecies from NuGet Package Manager:

nuget aditional extensions

Then I was able to run on any Windows or Linux version.

For reference, to create a Windows Service just need a batch to run as administrator:

Install.cmd

chcp 1252>NUL
SET mypath=%~dp0

sc create "service.name" displayname= "display.name" binpath= %mypath:~0,-1%\app-name.exe start= auto
sc description "service.name" "service description"

NET START service.name

pause

Uninstall.cmd

NET STOP service.name
sc delete "service.name"
pause
like image 39
Renan Ribeiro Avatar answered Jan 28 '26 05:01

Renan Ribeiro