15.02.2015 Views

C# 4 and .NET 4

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

1302 ❘ ChaPTer 43 windOws cOmmunicAtiOn fOundAtiOn<br />

<br />

<br />

<br />

<br />

<br />

<br />

<br />

<br />

<br />

<br />

<br />

<br />

<br />

<br />

<br />

<br />

<br />

hosTing<br />

WCF is very flexible when you are choosing a host to run the service. The host can be a Windows service,<br />

a COM+ application, WAS (Windows Activation Services) or IIS, a Windows application, or just a simple<br />

console application. When creating a custom host with Windows Forms or WPF, you can easily create a<br />

peer-to-peer solution.<br />

Custom hosting<br />

Let’s start with a custom host. The sample code shows hosting of a service within a console application;<br />

however, in other custom host types, such as Windows services or Windows applications, you can program<br />

the service in the same way.<br />

In the Main() method, a ServiceHost instance is created. After the ServiceHost instance is created,<br />

the application configuration file is read to define the bindings. You can also define the bindings<br />

programmatically, as shown earlier. Next, the Open() method of the ServiceHost class is invoked, so the<br />

service accepts client calls. With a console application, you need to be careful not to close the main thread<br />

until the service should be closed. Here, the user is asked to “press return” to exit the service. When the user<br />

does this, the Close() method is called to actually end the service:<br />

using System;<br />

using System.ServiceModel;<br />

public class Program<br />

{<br />

public static void Main()<br />

{<br />

using (var serviceHost = new ServiceHost())<br />

{<br />

serviceHost.Open();<br />

Console.WriteLine("The service started. Press return to exit");<br />

Console.ReadLine();<br />

}<br />

}<br />

}<br />

serviceHost.Close();<br />

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!