I'm trying to run a Web API application as a Windows Service using OWIN. However, I get the following message, when trying to start the service:
The [ServiceName] service on Local Computer started and then stopped. Some services stop automatically if they are not in use by other services or programs.
For some reason my service doesn't understand that it should keep listening to http://localhost:9000
The VS solution consists of two projects: The Web API and the Windows service.
In the Windows service project I have:
static class Program
{
static void Main()
{
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new Service()
};
ServiceBase.Run(ServicesToRun);
}
}
public partial class Service : ServiceBase
{
private const string _baseAddress = "http://localhost:9000/";
private IDisposable _server = null;
public Service()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
_server = WebApp.Start<Startup>(url: _baseAddress);
}
protected override void OnStop()
{
if (_server != null)
{
_server.Dispose();
}
base.OnStop();
}
}
In OnStart the Startup refers to the Startup class in the Web API project:
public class Startup
{
public void Configuration(IAppBuilder builder)
{
var config = new HttpConfiguration();
config.Routes.MapHttpRoute("Default",
"{controller}/{id}",
new { id = RouteParameter.Optional });
builder.UseWebApi(config);
}
}
(It also contains some configurations for Unity and logging.)
I guess the installer part of the Windows service project is mostly irrelevant, though it could be useful to know that I have:
this.serviceProcessInstaller.Account = System.ServiceProcess.ServiceAccount.LocalService;
What I've tried:
- To host the Web API using a console application and then host the console application as a Windows Service. But even though I included 'Console.ReadKey()', it simply stopped.
- To follow this guide: OWIN-WebAPI-Service The weird thing is that I can get his service to work, but when I tried changing my code to match his set-up, I kept getting the same error.
Full source code: github.com/SabrinaMH/RoundTheClock-Backend/tree/exploring_hosting