i need the window service for .net core that can be use to run and API
Loading
i need the window service for .net core that can be use to run and API
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Mayooran NavamanyRank #438 · 5.7K reputationPosted Jul 12, 2023, 5:54 AM EDT
Hi Isiaka
Go through the article
https://code-maze.com/aspnetcore-running-applications-as-windows-service/
Praveen Mishra183 reputationPosted Jul 13, 2023, 4:49 AM EDT
Hi Isiaka ,
Please follow these steps to create window service to run API.
using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Hosting; using System.IO; using System.Threading; using System.Threading.Tasks; namespace MyApiService { public class Program { public static void Main(string[] args) { // Run as a console application during debugging if (Debugger.IsAttached || args.Contains("--console")) { CreateHostBuilder(args).Build().Run(); } else { // Run as a Windows Service var pathToExe = Process.GetCurrentProcess().MainModule.FileName; var pathToContentRoot = Path.GetDirectoryName(pathToExe); Directory.SetCurrentDirectory(pathToContentRoot); var host = CreateHostBuilder(args).Build(); host.RunAsService(); } } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup(); }).UseWindowsService(); } public class MyApiService : IHostedService { private readonly IWebHost _webHost; public MyApiService(IWebHost webHost) { _webHost = webHost; } public Task StartAsync(CancellationToken cancellationToken) { return _webHost.StartAsync(cancellationToken); } public Task StopAsync(CancellationToken cancellationToken) { return _webHost.StopAsync(cancellationToken); } } }In this code, we have the
Programclass that serves as the entry point for our application. It checks whether the application is running in console mode or as a Windows Service. If it's running in console mode (e.g., during debugging), it starts the API using theCreateHostBuildermethod and runs it. If it's running as a Windows Service, it sets the content root directory and creates a host usingCreateHostBuilder, then callsRunAsService()to run the API as a Windows Service.The
MyApiServiceclass implements theIHostedServiceinterface, which allows the service to be started and stopped by the host. In theStartAsyncmethod, we start the web host, and in theStopAsyncmethod, we stop it.