Home > Net >  Modifying VS generated gRPC server code to run as Windows Service looks nothing like samples
Modifying VS generated gRPC server code to run as Windows Service looks nothing like samples

Time:08-09

I'm using Visual Studio 2022 to create a gRPC server and would like to turn it into a Windows Service. I've created and tested the server but when I look at the examples on the web, none of them look like the program.cs created by VS shown here:

using eTutorService.Services;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddGrpc();
var app = builder.Build();
app.MapGrpcService<eTutorServiceMain>();
app.MapGet("/", () => "Communication with gRPC must be made through a gRPC client...");
app.Run();

Everything I find adds "UseWindowsService" to CreateDefaultBuilder like the following:

Host.CreateDefaultBuilder(args)
    .UseWindowsService()
    ...

or

public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.UseWindowsService() // Enable running as a Windows service
.ConfigureWebHostDefaults(webBuilder =>
{
    webBuilder.UseStartup<Startup>();
});

But I can't find how the "CreateHostBuilder" stuff relates to the "WebApplication.CreateBuilder" code created by VS. CreateBuilder doesn't support .UseWindowsService and WebApplication doesn't support CreateDefaultBuilder.

EDIT: I was able to add UseWindowsService like this:

builder.Services.AddGrpc();
builder.Host
    .UseWindowsService(options =>
    {
        options.ServiceName = "CADE eTutor Core Service";
    });

It compiles and I added it to the Windows Services with that ServiceName using SC at the command line, but it fails to start with error 1053, "The service did not respond to the start or control request in a timely fashion".

Looking in the event log I see this error referencing the UseWindowService line.

Changing the host configuration using WebApplicationBuilder.Host is not supported. Use WebApplication.CreateBuilder(WebApplicationOptions) instead.

So I'm basically lost as to how to take the gRPC template created by VS and turn it into a Windows Service.

CodePudding user response:

Well, apparently Microsoft has changed how services are created, https://github.com/dotnet/AspNetCore.Docs/issues/23387 and I found the fix there. I can't say I really appreciate why this is necessary but the following code worked as far as allowing the program to run as a Windows Service:

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