15.02.2015 Views

C# 4 and .NET 4

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

simple service <strong>and</strong> Client ❘ 1287<br />

Custom service host<br />

WCF allows services to run in any host. You can create a Windows Forms or Windows Presentation<br />

Foundation (WPF) application for peer-to-peer services, or you can create a Windows service, or host the<br />

service with Windows Activation Services (WAS). A console application is also good to demonstrate a<br />

simple host.<br />

With the service host, you must reference the library RoomReservationService. The service is started<br />

by instantiating <strong>and</strong> opening an object of type ServiceHost. This class is defined in the namespace<br />

System.ServiceModel. The RoomReservationService class that implements the service is defined in the<br />

constructor. Invoking the Open() method starts the listener channel of the service — the service is ready to<br />

listen for requests. The Close() method stops the channel.<br />

using System;<br />

using System.ServiceModel;<br />

namespace Wrox.ProCSharp.WCF<br />

{<br />

class Program<br />

{<br />

internal static ServiceHost myServiceHost = null;<br />

internal static void StartService()<br />

{<br />

myServiceHost = new ServiceHost(typeof(RoomReservationService));<br />

myServiceHost.Open();<br />

}<br />

internal static void StopService()<br />

{<br />

if (myServiceHost.State != CommunicationState.Closed)<br />

myServiceHost.Close();<br />

}<br />

static void Main()<br />

{<br />

StartService();<br />

Console.WriteLine("Server is running. Press return to exit");<br />

Console.ReadLine();<br />

}<br />

}<br />

}<br />

StopService();<br />

code snippet RoomReservationServiceHost/Program.cs<br />

For the WCF configuration, you need to copy the application configuration file that was created with<br />

the service library to the host application. You can edit this configuration file with the WCF Service<br />

Configuration Editor (see Figure 43-5).<br />

Using the custom service host, you can deselect the WCF option to start the WCF Service Host in the project<br />

settings of the WCF library.<br />

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!