Hosting


WCF is very flexible when choosing a host to run the service. The host can be a Windows Service, a COM+application, ASP.NET, a Windows application, or just a simple console application. When creating a custom host with Windows Forms, you can easily create a peer-to-peer solution.

The sample code shows hosting of a service within a console application. In the Main() method, a ServiceHost instance is created. After the ServiceHost instance is created, the application configuration file is read to define the bindings. You can also define the bindings programmatically, as shown earlier. Next, the Open() method of the ServiceHost class is invoked, so the service accepts client calls. With a console application, you have to pay attention not to close the main thread until the service should be closed. Here, the user is asked to end the service when the Close() method is invoked.

  using System; using System.ServiceModel; public class Program {    public static void Main()    {       using (ServiceHost serviceHost = new ServiceHost())       {          serviceHost.Open();          Console.WriteLine("The service started. Press return to exit");          Console.ReadLine();          serviceHost.Close();       }    } } 

To abort the service host, you can invoke the Abort() method of the ServiceHost class. To get the current state of the service, the State property returns a value defined by the CommunicationState enumeration. Possible values are Created, Opening, Opened, Closing, Closed, and Faulted.

Important 

If you start the service from within a Windows Forms application and the service code invokes methods of Windows Forms controls, you must pay attention that only the control’s creator thread is allowed to access the methods and properties of the control. With WCF, this behavior can be achieved easily by setting the UseSynchronizatonContext property of the attribute [ServiceBehavior].

With ASP.NET hosting, you get the features from the ASP.NET worker process like automatic activation of the service, health monitoring, and process recycling.

For using ASP.NET hosting, you just have to create a .svc file with the ServiceHost declaration that includes the language and the name of the service class (here the class is Wrox.ProCSharp.WCF .RoomReservationService). In addition, you must specify the file that contains the service class.

  <%@ServiceHost language="C#" Service="RoomReservationService"       CodeBehind="~/App_Code/RoomReservationService.cs" %> 

Tip 

You can also add a WCF service to Enterprise Service components. This is discussed in Chapter 38.




Professional C# 2005 with .NET 3.0
Professional C# 2005 with .NET 3.0
ISBN: 470124725
EAN: N/A
Year: 2007
Pages: 427

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net