WCF (Windows Communication Foundation) services can be hosted in different environments:
- in IIS launched as a web service
- in WAS running e.g. as a Windows Service
- self hosted in any kind of application
Self hosting is quite simple as the following sample code illustrates.
For self hosted applications the host application needs to be started before a client can access the service.
WCF services hosted in IIS are launched when a client application accesses the web service URL.
C# Sample code of a WCF Host Application
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Windows.Forms;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Dispatcher;
namespace WCFHost
{
public partial class Form1 : Form
{
ServiceHost serviceHost = null;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
try
{
// Create a ServiceHost for the XML DA service
serviceHost = new ServiceHost(typeof(opcxml.OpcXmlDA));
// Open the ServiceHost to create listeners and start listening for messages.
serviceHost.Open();
EventLog.WriteEntry("WCFselfHost", "The service is now available", EventLogEntryType.Information);
tbInfo.Text = "The service is now available.\r\nThe configured Endpoint Listeners are:";
foreach (ChannelDispatcher cd in serviceHost.ChannelDispatchers)
{
foreach (EndpointDispatcher epd in cd.Endpoints)
{
tbInfo.Text += "\r\n " + epd.EndpointAddress.Uri.AbsoluteUri;
}
}
}
catch (Exception ex)
{
tbInfo.Text = ex.Message;
if(serviceHost !=null)
serviceHost.Abort();
}
}
//---------------------------------------------------------
void Form1_FormClosing(object sender, System.Windows.Forms.FormClosingEventArgs e)
{
if (serviceHost != null)
{
serviceHost.Close();
serviceHost.Abort();
}
}
}
}