'How to host a web API in a windows service?

I have created and started a windows service (with exe as MyService.exe) using C# on the other hand I follow up this link for self-hosting: https://codeopinion.com/self-host-asp-net-web-api/.

When I want to combine the windows service and self-hosting web API the OnStart method become like This :

 protected override void OnStart(string[] args)
    {
        ServiceStatus serviceStatus = new ServiceStatus();
        serviceStatus.dwCurrentState = ServiceState.SERVICE_START_PENDING;
        serviceStatus.dwWaitHint = 100000;
        SetServiceStatus(this.ServiceHandle, ref serviceStatus);

        using (WebApp.Start<Startup>("http://localhost:8080"))
        {
            Console.WriteLine("Web Server is running.");
            Console.WriteLine("Press any key to quit.");
            Console.ReadLine();
        }

        System.Timers.Timer timer = new System.Timers.Timer();
        timer.Interval = 300000; // 120 sanieh
        timer.Elapsed += new ElapsedEventHandler(this.OnTimer);
        timer.Start();


        serviceStatus.dwCurrentState = ServiceState.SERVICE_RUNNING;
        SetServiceStatus(this.ServiceHandle, ref serviceStatus);
    }

The service runs but it does not call, unfortunately. Is there any solution that can host a web API in Windows service? Thanks in advance for taking the time to ask my question



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source