How to configure an ASP.NET Core 7 Web API as a Windows service?

53 Views Asked by At

I am creating an ASP.NET Core 7 Web API and need to run it hosted as a Windows service. I've read the documentation but can't find a solution.

I tested this in my program.cs, but I see this error in the event viewer:

The "my service" service could not be started due to the following error:
The service did not respond to the start or control request in a timely manner.

builder.Services.AddWindowsService();

var app = builder.Build();

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

app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

if (OperatingSystem.IsWindows())
{
    app.Services.GetRequiredService<IHostApplicationLifetime>().ApplicationStarted.Register(() =>
        {
            ServiceBase.Run(new ServiceBase[] { new MyWindowsService(app) });
        });
}
else
{
    app.Run();
}

class MyWindowsService : ServiceBase
{
    private readonly IHost _host;

    public MyWindowsService(IHost host)
    {
        _host = host;
    }

    protected override void OnStart(string[] args)
    {
        _host.Start();
    }

    protected override void OnStop()
    {
        _host.Dispose();
    }
}
1

There are 1 best solutions below

2
Ronnie Souza On

I managed to solve this problem by just adding the following code.

builder.Host.UseWindowsService();

so, my Program.cs class looked like this:

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Host.UseWindowsService();

var app = builder.Build();

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

app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();

app.Run();