Creé un nuevo proyecto ASP.NET Core con Visual Studio 2022 Preview y estoy tratando de ejecutarlo como un servicio de Windows. Descargué el último paquete Microsoft.Extensions.Hosting.WindowsServices (6.0.0-preview.7.21377.19).
Al investigar en línea, la función .UseWindowsService() entra en el método CreateHostBuilder. Pero en la nueva plantilla se ve diferente. No puedo entender dónde debo llamar a .UseWindowsService en la nueva plantilla. Este es mi código actual, parece que el servicio se está iniciando, pero luego, cuando busco localhost: 5000, aparece el error 404
using Microsoft.OpenApi.Models; using Microsoft.Extensions.Hosting.WindowsServices; var builder = WebApplication.CreateBuilder(args); builder.Host.UseWindowsService(); // <--- Added this line // Add services to the container. builder.Services.AddControllers(); builder.Services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new() { Title = "MyWindowsService", Version = "v1" }); }); var app = builder.Build(); // Configure the HTTP request pipeline. if (builder.Environment.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseSwagger(); app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "MyWindowsService v1")); } app.UseAuthorization(); app.MapControllers(); app.Run();Publiqué mi service exe así
dotnet publish -c Release -r win-x64 --self-containedLa siguiente codificación establece el tiempo de vida en WindowsServiceLifetime y habilita el registro en el registro de eventos. En la mayoría de los casos, esto debería ser todo lo que necesita para ejecutar la aplicación como un servicio de Windows.
if (WindowsServiceHelpers.IsWindowsService()) { appBuilder.Services.AddSingleton<IHostLifetime, WindowsServiceLifetime>(); appBuilder.Logging.AddEventLog(settings => { if (string.IsNullOrEmpty(settings.SourceName)) { settings.SourceName = appBuilder.Environment.ApplicationName; } }); }Ya que simplemente usando
builder.Host.UseWindowsService();no funcionará con WebApplication.CreateBuilder() ( ver ), sino que lanzará la excepción
Exception Info: System.NotSupportedException: The content root changed from "C:\Windows\system32\" to "...". Changing the host configuration using WebApplicationBuilder.Host is not supported. Use WebApplication.CreateBuilder(WebApplicationOptions) instead.o más bien causará este error
Start-Service : Service 'Service1 (Service1)' cannot be started due to the following error: Cannot start service Service1 on computer '.'.al intentar iniciar el servicio con Start-Service en PowerShell, encontré una solución que funcionó para mí
using Microsoft.Extensions.Hosting.WindowsServices; var options = new WebApplicationOptions { Args = args, ContentRootPath = WindowsServiceHelpers.IsWindowsService() ? AppContext.BaseDirectory : default }; var builder = WebApplication.CreateBuilder(options); builder.Host.UseWindowsService();