Host WCF in winform and pass the winform variable to WCF and wcfwinform
Recently, the customer requested that the two functions in the server program be provided as services for convenient calls. First, we want to create a separate project for the wcf service. However, to use the variables in the winform of the server program, we can only add one item for the wcf service in winform. The procedure is as follows:
1. Add the wcf service item in winform
<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" />
<baseAddresses>
<add baseAddress="http://localhost:8111/BroadcastService" />
</baseAddresses>
</service>
</services>
</system.serviceModel>
In the following line, I made it a little simpler. The default address is too long:
<Add baseAddress = "http: // localhost: 8111/BroadcastService"/>
2. Define the service. Here I use the constructor to pass in the variables in 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. host wcf Service in the form load event and close in the closed event:
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();
}
Note the following two rows to pass the variables:
BroadcastService broadcastSvc = new BroadcastService (this. rapidServerEngine, orayCache );
M_Host = new ServiceHost (broadcastSvc );
It can be simplified
M_Host = new ServiceHost (typeof (BroadcastService ))
4. Add properties to the wcf Service Class
[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
public class BroadcastService : IBroadcastService
5. After the winform program is started, you can access the wcf address defined in step 1.
<Add baseAddress = "http: // localhost: 8111/BroadcastService"/>
Access http: // localhost: 8111/BroadcastService.
Crazy kiss IT