最近客户要求把服务器端程序里的二个功能用service的方式提供出来,方便调用。首先想着单独建一个wcf 服务的项目,但是因为要用到server端程序winform里的变量,因此只能在winform里添加一个wcf service的item。下面介绍详细的操作步骤:
1. winform里添加wcf service的item
添加之后,app.config里会自动加上wcf的配置项:
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name="">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="true" />
</behavior>
</serviceBehaviors>
</behaviors>
<services>
<service name="OrayTalk.Server.Broadcast.BroadcastService">
<endpoint address="" binding="basicHttpBinding" contract="OrayTalk.Server.Broadcast.IBroadcastService">
<identity>
<dns value="localhost" />
</identity>
</endpoint>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
<host>
<baseAddresses>
<add baseAddress="http://localhost:8111/BroadcastService" />
</baseAddresses>
</host>
</service>
</services>
</system.serviceModel>
其中下面这行,我把它改得简单了一点,默认的地址太长:
<add baseAddress="http://localhost:8111/BroadcastService" />
2. 定义好service,这里我用构造函数把winform里的变量传进来:
public class BroadcastService : IBroadcastService
{
public static IRapidServerEngine m_RapidServerEngine;
public static IOrayCache m_OrayCache;
public BroadcastService(IRapidServerEngine rapidServerEngine, IOrayCache orayCache)
{
m_RapidServerEngine = rapidServerEngine;
m_OrayCache = orayCache;
}
...
}
3. 在form的load事件里host wcf服务, closed事件里关闭:
ServiceHost m_Host;
private void MainServerForm_Load(object sender, EventArgs e)
{
try
{
BroadcastService broadcastSvc = new BroadcastService(this.rapidServerEngine, orayCache);
m_Host = new ServiceHost(broadcastSvc);
m_Host.Open();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void MainServerForm_FormClosed(object sender, FormClosedEventArgs e)
{
m_Host.Close();
}
这里要注意的是下面二行,把变量传递进去:
BroadcastService broadcastSvc = new BroadcastService(this.rapidServerEngine, orayCache);
m_Host = new ServiceHost(broadcastSvc);
如果不用传变量到wcf服务里,可以简化成
m_Host = new ServiceHost(typeof(BroadcastService))
4. wcf服务类上加上属性
[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
public class BroadcastService : IBroadcastService
5. 启动winform程序后,就可以访问在第一步里定义的wcf地址了
<add baseAddress="http://localhost:8111/BroadcastService" />
这时访问http://localhost:8111/BroadcastService即可。