最近客戶要求把服務器端程序里的二個功能用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即可。