I need to host a WCF service inside a Windows Forms application and call the WCF service from a Windows service that will send data to the WCF service which will show it in the Windows Forms application (desktop application).
How can I implement this? I need code that is working correctly and tried before.
This code should be enough to get you started:
namespace TestWinform
{
public partial class Form1 : Form
{
private ServiceHost Host;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
Host = new ServiceHost(typeof(MyWcfService));
Host.Open();
}
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
Host.Close();
}
}
}
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name="TestWinform.MyWcfServiceBehavior">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="false" />
</behavior>
</serviceBehaviors>
</behaviors>
<services>
<service behaviorConfiguration="TestWinform.MyWcfServiceBehavior"
name="TestWinform.MyWcfService">
<endpoint address="" binding="wsHttpBinding" contract="TestWinform.IMyWcfService">
<identity>
<dns value="localhost" />
</identity>
</endpoint>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
<host>
<baseAddresses>
<add baseAddress="http://localhost:8080/MyWcfService/" />
</baseAddresses>
</host>
</service>
</services>
</system.serviceModel>
</configuration>
Note that the App.config has been generated by Visual Studio when I added a WCF Service to my project.
I recomend you to also use a Thread:
private void Form1_Load(object sender, EventArgs e)
{
Task.Factory.StartNew(() =>
{
host = new ServiceHost(typeof(AssinadorWcf.AssinadorDigitalLecom));
host.Open();
});
}
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
try
{
host.Close();
}
catch
{
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With