Книга: C# 2008 Programmer

Consuming the WCF Service

Consuming the WCF Service

The example you just created is a WCF Service Library. The useful aspect of the project is that it includes the WCF Test Client, which enables you to test your WCF easily without needing to build your own client. In this section, you build a Windows application to consume the service.

Add a Windows Forms Application project to the current solution, and name it ConsumeWCFService.

Add a service reference to the WCF service created in the previous section. Because the WCF Service is in the same solution as the Windows Forms application, you can simply click the Discover button in the Add Service Reference dialog to locate the service (see Figure 20-15).


Figure 20-15

Use the default ServiceReference1 name, and click OK. Visual Studio 2008 automatically adds the two libraries — System.Runtime.Serialization.dll and System.ServiceModel.dll — to your project (see Figure 20-16). The proxy class ServiceReference1 is the reference to the WCF service.


Figure 20-16

Double-click on Form1, and in the Form1_Load event handler, code the following:

private void Form1_Load(object sender, EventArgs e) {
 //---create an instance of the service---
 ServiceReference1.Service1Client client =
  new ConsumeWCFService.ServiceReference1.Service1Client();
 //---create an instance of the Contact class---
 ServiceReference1.Contact c =
  new ConsumeWCFService.ServiceReference1.Contact() {
   Name = "Wei-Meng Lee", YearofBirth = 1990
  };
 //---calls the service and display the result---
 MessageBox.Show(client.getAge(c).ToString());
 //---close the client---
 client.Close();
}

Calling the WCF service is very similar to consuming an ASMX Web Service — create an instance of the proxy class, call the service's operation, pass in the required parameters, and wait for the result from the service.

Set the Windows Forms application as the startup project, and press F5. A message box appears, displaying 18.

Оглавление книги


Генерация: 1.254. Запросов К БД/Cache: 3 / 1
поделиться
Вверх Вниз