我正在尝试在Windows窗体应用程序中运行WCF服务。我复制并修改了Microsoft的WCF示例中的代码。运行WCF Sample时,服务显示在我使用的端口监视器(CurrPorts)中。当我运行我的代码时,我看不到我的服务......
这是我的代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
namespace NoName.Server
{
[ServiceContract(Namespace="http://NoName")]
public interface IApplicationService
{
[OperationContract()]
NoName.Entities.MediaParameter[] GetParametersForMediaObject(string mediaObjectId);
[OperationContract()]
NoName.Entities.MediaParameter GetMediaParameter(string parameterId);
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace NoName.Server
{
public class ApplicationService : IApplicationService
{
public Entities.MediaParameter[] GetParametersForMediaObject(string mediaObjectId)
{
throw new NotImplementedException();
}
public Entities.MediaParameter GetMediaParameter(string parameterId)
{
throw new NotImplementedException();
}
}
}
我正在从表单
运行它private void toolStripButton1_Click(object sender, EventArgs e)
{
using (ServiceHost host = new ServiceHost(typeof(ApplicationService)))
{
host.Open();
}
}
app.config中的配置:
<system.serviceModel>
<services>
<service name="NoName.Server.ApplicationService" behaviorConfiguration="ApplicationServiceBehavior">
<host>
<baseAddresses>
<add baseAddress="http://localhost:8000/NoName/ApplicationService"/>
</baseAddresses>
</host>
<!-- this endpoint is exposed at the base address provided by host: http://localhost:8000/NoName/ApplicationService -->
<endpoint address="" binding="wsHttpBinding" contract="NoName.Server.IApplicationService"/>
<!-- the mex endpoint is exposed at soap.tcp://localhost:8000/NoName/ApplicationService/mex -->
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
</service>
</services>
<!--For debugging purposes set the includeExceptionDetailInFaults attribute to true-->
<behaviors>
<serviceBehaviors>
<behavior name="ApplicationServiceBehavior">
<serviceMetadata httpGetEnabled="True"/>
<serviceDebug includeExceptionDetailInFaults="False"/>
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
它运行时没有错误编译,没有异常。它不会存在。想法?
答案 0 :(得分:2)
嗯 - 你正在使用using
块,这通常是一件好事 - 但是在这里,服务主机将在using
块的末尾立即再次关闭 - 这是当然不你想要的东西!
using (ServiceHost host = new ServiceHost(typeof(ApplicationService)))
{
host.Open(); // host is opened here
} // host is disposed and closed here
所以你的ServiceHost
已经打开并准备好接收请求 - 仅仅几分之一秒......然后它被关闭并被处理掉,因为using { .. }
块已经结束.....
您需要做的是:
将私有成员变量添加到例如你的主要表格
private ServiceHost _serviceHost = null;
在代码中的某个位置打开该服务主机,例如在你的方法中你有:
private void toolStripButton1_Click(object sender, EventArgs e)
{
_serviceHost = new ServiceHost(typeof(ApplicationService));
}
将其打开,直到例如Winforms应用程序关闭(或用户选择其他菜单项以实际关闭服务主机)