Learning WCF Chapter1 Creating a New Service from Scratch

Source: Internet
Author: User
Tags hosting

You'll be introduced to the WCF service.
This lab isn ' t your typical "Hello World"-it's "Hello Indigo"!
In this lab,you would learn how to build a new WCF service and in the process learn the minimum requirements of service dev Elopment and consumption.
Here's a short list of things you ' ll accomplish:

Create a new service contract and service implementation
programmatically Configure a service host, its endpoints, and bindings
Create a client application and open a client channel proxy to invoke the service

Now,before you start thinking ' been there,done that, ' This simple lab would be slightly different
Because I ' m going to give you some practical design tips that ensure configurability and appropriate decoupling of service , Host,and client.
In Addition,i ' ll is diving deeper into basic concepts such as Services,service contracts,endpoints, bindings, ServiceHost, and channels.

Lab:creating Clients and Services programmatically

In this first lab,you would create a new solution with three projects:a service,a host,and a client.
When you run the service host,you ' ll expose a single service endpoint.
The client application would access service operations through that endpoint.
You'll host the service in a console application and invoke the service using a manually constructed proxy.
This lab would teach you the basic requirements for creating,hosting,and consuming a service with WCF.

Creating a new service
The first thing you'll do are create a new service contract with a single operation and implement this contract on a new Service type.
1. Lab,everything begins from Scratch,so to start by creating a new Visual Studio solution.
Open a new instance of Visual Studio 2008.
Select File? New? Project,and from the new Project dialog,create a New Blank solution in the <yourlearningwcfpath>\labs\chapter1 Direc Tory.
Name the solution Servicefromscratch. Verify the. NET Framework version selected in the dropdown list are set to the. NET Framework 3.0 or. NET Framework 3.5.
Click OK to create the empty solution.

2. Create the service project.
From Solution Explorer,right-click on the Solution node and select Add? New Project.
Select the Class Library template,name the project Helloindigo,and make sure the location path matches the solution at < ; Yourlearningwcfpath>\labs\chapter1\servicefromscratch.
Click OK to create the new project.


3. Now you'll create your first service contract.
From Solution Explorer,rename the project's only class file to Service.cs.
Open This file in the Code window.
ADD a new interface named Ihelloindigoservice in Service.cs.
Add a single method to the interface, Helloindigo, and the signature shown here:

 Public Interface ihelloindigoservice{string  Helloindigo ();}

4. Add a reference to the System.ServiceModel assembly. From Solution Explorer,right-click References and select System.ServiceModel from the list.
You'll also need to add the following using statement to Service.cs:

using System.ServiceModel;

5. To turn the interface-a service contract,you ' ll need to explicitly decorate the interface with the Servicecontrac Tattribute.
In Addition,each method should is decorated with the operationcontractattribute to include it in the service contract.
In this case,you ' ll make Ihelloindigoservice a service contract and expose Helloindigo () as their only service operation by Applying these attributes as shown here:

[ServiceContract (namespace="http://www.thatindigogirl.com/samples/2006/06")]  Publicinterface  ihelloindigoservice{[operationcontract]string  Helloindigo ();}

Note:providing a namespace for the ServiceContractAttribute reduces the possibility in naming collisions with other Servic Es. This would be discussed in greater detail in Chapter 2.

6. The same file,create a service type to implement the service contract.
You can modify the existing class definition,renaming it to Helloindigoservice.
Then add the Ihelloindigoservice interface to the derivation list and implement Helloindigo () with the following code:

 Public class helloindigoservice:ihelloindigoservice{publicstring  Helloindigo () {  return"Hello Indigo";}}

7. Compile the service project.

At the Point,you ' ve created a service contract with a single operation and implemented it on a service type.
The service is all at this point,but to consume it from a client application, and you'll need to host it first.

Hosting a service
Next,add a new console application to the solution.
This would be the host application.
You'll instantiate a ServiceHost instance for the service type and configure a single endpoint.
1. Go to the solution Explorer and add a new Console application project to the solution.
Name the new project Host.
2. Add a reference to the System.ServiceModel Assembly,and add the following using statement to Program.cs:

using System.ServiceModel;

3. You'll be writing code to host the Helloindigoservice type.
Before you can do this and you must add a reference to the Helloindigo project.
4. Create a ServiceHost instance and endpoint for the service.
Open Program.cs in the Code window and modify the Main () entry point,adding the code shown in Example 1-1.

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.ServiceModel;namespacehost{classProgram {Static voidMain (string[] args) {            using(ServiceHost host =NewServiceHost (typeof(Helloindigo.helloindigoservice),NewUri ("Http://localhost:8000/HelloIndigo")) {host. AddServiceEndpoint (typeof(Helloindigo.ihelloindigoservice),NewBasicHttpBinding (),"Helloindigoservice"); Host.                Open (); Console.WriteLine ("Press <ENTER> to terminate the service host");            Console.ReadLine (); }        }    }}

Example 1-1. Code to programmatically initialize the ServiceHost

This code initializes a ServiceHost instance specifying the service type and a base address where relative service Endpoin TS can be located.
It also adds a single relative endpoint for the service.
In this Case,a base address are provided for HTTP Protocol,and the relative endpoint uses one of the standard bindings, Bas Ichttpbinding, based on HTTP protocol.
5. Compile and run the host to verify that it works.
From Solution Explorer,rightclick on the Host project node and select "Set as Startup project."
Run the project (F5), and you should see console output similar to that shown in Figure 1-17.

Figure 1-17. Console output for the host application
6. Stop debugging and return to Visual Studio.
You are now having a host application for the service.
When it was running clients would be able to communicate with the service.
The next step is to create a client application.

Creating a proxy to invoke a service
Now you'll create a new console application to test the service.
To does this,the client requires metadata from the service and information on its endpoint.
This information is used to initialize a client proxy that can invoke service operations.

1. Go to Solution Explorer and add a new Console application to the solution.
Name the new project Client.
2. As you might expect,this project also requires a reference to System.ServiceModel.
Add this reference and add the following using statement to Program.cs:

using System.ServiceModel;

3. Copy the service contract to the client.
First,add a new class to the Client project,naming the file ServiceProxy.cs.
Open This new file in the Code window and add the Ihelloindigoservice contract metadata as shown in Example 1-2.

Example 1-2. Service contract metadata for the client

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.ServiceModel;namespaceclient{[ServiceContract (Namespace="http://www.thatindigogirl.com/samples/2006/06")]     Public InterfaceIhelloindigoservice {[OperationContract]stringHelloindigo (); }}

This service contract supplies the necessary metadata to the Client,describing namespaces and service operation signatures .
4. Now, can add code to invoke the service endpoint.
Open Program.cs and modify the Main () entry point by adding the code as shown in Example 1-3.

Example 1-3. Code to invoke a service through its generated proxy

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.ServiceModel;namespaceclient{classProgram {Static voidMain (string[] args) {endpointaddress EP=NewEndpointAddress ("Http://localhost:8000/HelloIndigo/HelloIndigoService"); Ihelloindigoservice Proxy= Channelfactory<ihelloindigoservice>. CreateChannel (NewBasicHttpBinding (), EP); strings =Proxy.            Helloindigo ();            Console.WriteLine (s); Console.WriteLine ("Press <ENTER> to terminate Client.");        Console.ReadLine (); }    }}

This code uses the ChannelFactory to create a new channel to invoke the service.
This strongly typed channel reference acts as a proxy.
The code also initializes an endpointaddress with the correct address and binding expected by the service endpoint.
5. Test the client and service.
Compile the solution and run the Host project first,followed by the Client project.
The Client console output should look similar to, shown in Figure 1-18.

In the next few sections,i would explain in + detail the steps you completed and
The features explored in the lab.

Learning WCF Chapter1 Creating a New Service from Scratch

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.