2

I've seen a few variants of this issue, but none are quite the same as my issue.

I'm building a Windows Service, using .NET 6.0. This service hosts ASP.NET Core in addition to other background functionality. When run as an ordinary application, everything is fine, but when registered as a service, on startup it fails with:

Application: MyService.exe
CoreCLR Version: 6.0.222.6406
.NET Version: 6.0.2
Description: The process was terminated due to an unhandled exception.
Exception Info: System.NotSupportedException: The content root changed from "C:\WINDOWS\system32\" to "c:\long-path-executable\". Changing the host configuration using WebApplicationBuilder.Host is not supported. Use WebApplication.CreateBuilder(WebApplicationOptions) instead.
   at Microsoft.AspNetCore.Builder.ConfigureHostBuilder.ConfigureHostConfiguration(Action`1 configureDelegate)
   at Microsoft.Extensions.Hosting.HostingHostBuilderExtensions.UseContentRoot(IHostBuilder hostBuilder, String contentRoot)
   at Microsoft.Extensions.Hosting.WindowsServiceLifetimeHostBuilderExtensions.UseWindowsService(IHostBuilder hostBuilder, Action`1 configure)
   at Program.Main(String[] args) in C:\...\Program.cs:line 41

The error message is quite specific - use WebApplication.Createbuilder. Problem is, that's exactly what I am already doing. Here's my program startup code:

      var builder = WebApplication.CreateBuilder(args);

      builder.Host.UseWindowsService(options =>
      {
        options.ServiceName = "FileFlow";
      });

      builder.Services.AddControllers();
      builder.Services.AddEndpointsApiExplorer();
      builder.Services.AddSwaggerGen();
      builder.Services.AddHostedService<WindowsService>();

      var app = builder.Build();

      if (app.Environment.IsDevelopment())
      {
        app.UseSwagger();
        app.UseSwaggerUI();
      }

      app.UseAuthorization();
      app.MapControllers();
      app.Run();

As you can see from the stack trace, it's failing very early in the build process.

Suggestions appreciated. Meanwhile, I'll keep digging.

CarlDaniel
  • 333
  • 3
  • 16

1 Answers1

3

This other post https://stackoverflow.com/a/70036550/4139809 has the answer:

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

Thanks to Jeremy Lakeman for the pointer to that post in the comments.

CarlDaniel
  • 333
  • 3
  • 16