Hosting WCF service inside a Windows Forms application

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.

Leave a Comment