在 windows 服务上托管 ApiController
Hosting ApiControllers on windows service
我有一个 REST API 项目,背后有控制器和服务,它在 IIS 上运行良好。
现在我正在尝试寻找一种方法将其作为 windows 服务托管在非 IIS 计算机上。到目前为止运气不好,TopShelf 似乎是我想要的,但我有多个 controllers/services 可以托管,而且它似乎一次只能处理一个。
有没有办法拥有一个 windows 服务项目 运行 另一个(引用的)项目并托管它?不用每次都卸载安装服务更容易调试,所以理想情况下项目将保持独立。
您可以在 windows 服务中托管 WCF 服务。为此,请创建一个 windows 服务项目并在您的 windows 服务项目中引用 WCF project.Also 添加 System.ServiceModel
和 System.ServiceModel.Description
dll,然后编写如下函数这个
private ServiceHost host;
private void HostWcfService()
{
//Create a URI to serve as the base address
Uri httpUrl = newUri("http://localhost:1256/MyService/Service");
//Create ServiceHost
host = newServiceHost(typeof(MyService.IService), httpUrl);
//Add a service endpoint
host.AddServiceEndpoint(typeof(MyService.IService), newWSHttpBinding(), "");
//Enable metadata exchange
ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
smb.HttpGetEnabled = true;
host.Description.Behaviors.Add(smb);
//Start the Service
host.Open();
}
然后像这样在 OnStart 方法中调用 HostWcfService()
protected override void OnStart(string[] args)
{
if (host != null)
{
host.Close();
}
HostWcfService();
}
并像这样更新 OnStop 方法
protected override void OnStop()
{
if (host != null)
{
host.Close();
host = null;
}
}
我有一个 REST API 项目,背后有控制器和服务,它在 IIS 上运行良好。
现在我正在尝试寻找一种方法将其作为 windows 服务托管在非 IIS 计算机上。到目前为止运气不好,TopShelf 似乎是我想要的,但我有多个 controllers/services 可以托管,而且它似乎一次只能处理一个。
有没有办法拥有一个 windows 服务项目 运行 另一个(引用的)项目并托管它?不用每次都卸载安装服务更容易调试,所以理想情况下项目将保持独立。
您可以在 windows 服务中托管 WCF 服务。为此,请创建一个 windows 服务项目并在您的 windows 服务项目中引用 WCF project.Also 添加 System.ServiceModel
和 System.ServiceModel.Description
dll,然后编写如下函数这个
private ServiceHost host;
private void HostWcfService()
{
//Create a URI to serve as the base address
Uri httpUrl = newUri("http://localhost:1256/MyService/Service");
//Create ServiceHost
host = newServiceHost(typeof(MyService.IService), httpUrl);
//Add a service endpoint
host.AddServiceEndpoint(typeof(MyService.IService), newWSHttpBinding(), "");
//Enable metadata exchange
ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
smb.HttpGetEnabled = true;
host.Description.Behaviors.Add(smb);
//Start the Service
host.Open();
}
然后像这样在 OnStart 方法中调用 HostWcfService()
protected override void OnStart(string[] args)
{
if (host != null)
{
host.Close();
}
HostWcfService();
}
并像这样更新 OnStop 方法
protected override void OnStop()
{
if (host != null)
{
host.Close();
host = null;
}
}