我正在尝试使用 OWIN 将 Web API 应用程序作为 Windows 服务运行。但是,在尝试启动服务时,我收到以下消息:
本地计算机上的 [ServiceName] 服务启动然后停止。如果其他服务或程序未使用某些服务,则会自动停止。
由于某种原因,我的服务不明白它应该继续监听http://本地主机:9000 http://localhost:9000
VS 解决方案由两个项目组成:Web API 和 Windows 服务。
在 Windows 服务项目中我有:
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指的是StartupWeb API 项目中的类:
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);
}
}
(它还包含一些 Unity 和日志记录的配置。)
我想 Windows 服务项目的安装程序部分大部分是无关紧要的,尽管知道我有:
this.serviceProcessInstaller.Account = System.ServiceProcess.ServiceAccount.LocalService;
我尝试过的:
- 使用控制台应用程序托管 Web API,然后将控制台应用程序托管为 Windows 服务。但即使我包含了“Console.ReadKey()”,它还是停止了。
- 要遵循本指南:OWIN-WebAPI-服务 https://github.com/danesparza/OWIN-WebAPI-Service奇怪的是,我可以让他的服务正常工作,但是当我尝试更改代码以匹配他的设置时,我不断收到相同的错误。
完整源代码:github.com/SabrinaMH/RoundTheClock-Backend/tree/exploring_hosting