Search code examples
windows-services.net-6.0

.NET 6 UseWindowsService() throws exception


Here's my "ENTIRE" code in program.cs.

var builder = WebApplication.CreateBuilder(args);

builder.Host.UseWindowsService();

// Add services to the container.
builder.Services.AddGrpc();

var app = builder.Build();

// Configure the HTTP request pipeline.
app.MapGrpcService<GreeterService>();
app.MapGet("/", () => "error");

app.Run();

Packages:

  • Grpc.AspNetCore(2.47.0)
  • Microsoft.Extensions.Hosting.WindowsServices (6.0.0)

I deployed this a test server and tried to start the service...and I got this in the Event Log:

Application: PartReservationGrpc.exe CoreCLR Version: 6.0.622.26707 .NET Version: 6.0.6 Description: The process was terminated due to an unhandled exception. Exception Info: System.NotSupportedException: The content root changed from "C:\windows\system32" to "D:\CMAP\iceman\partreservation". Changing the host configuration using WebApplicationBuilder.Host is not supported. Use WebApplication.CreateBuilder(WebApplicationOptions) instead. at Microsoft.AspNetCore.Builder.ConfigureHostBuilder.ConfigureHostConfiguration(Action1 configureDelegate) at Microsoft.Extensions.Hosting.HostingHostBuilderExtensions.UseContentRoot(IHostBuilder hostBuilder, String contentRoot) at Microsoft.Extensions.Hosting.WindowsServiceLifetimeHostBuilderExtensions.UseWindowsService(IHostBuilder hostBuilder, Action1 configure) at Microsoft.Extensions.Hosting.WindowsServiceLifetimeHostBuilderExtensions.UseWindowsService(IHostBuilder hostBuilder) at Program.$(String[] args) in C:\Users\WuJ22\source\Workspaces\C5CG2133PXF\gRPC\PartReservation\PartReservation\PartReservationGrpc\Program.cs:line 33

line 33: is exactly where the UseWindowsService() is made.

Has anyone run into this issue?


Solution

  • Answer can be found here:

    The trick is calling the CreateBuilder() with the WebApplicationOptions to set the ContentRootPath.