Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hosting WCF service inside a Windows Forms application

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.

like image 753
Ahmy Avatar asked Mar 08 '11 11:03

Ahmy


2 Answers

This code should be enough to get you started:

Form1.cs

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();
        }
    }
}

App.config

<?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.

like image 65
Keeper Avatar answered Oct 31 '22 18:10

Keeper


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
        {
        }
    }
like image 21
Rogerio Gelonezi Avatar answered Oct 31 '22 18:10

Rogerio Gelonezi