首先认识一下WCF里几个重要的概念,ABCB
A:Address(Where)指定message传递的位置(包含client和server),它是一个URI,其中URI Schema用来标识传输协议。
B:Binding(How)指定message专递的方式(transport, encoding…)。
C:Contract(What)指定message的结构
B:Behaviors是用来加到Server(service behavior)或Client(endpoint behavior)上,表示一种额外的行为。
具体WCF工作的基本方式可以通过下图来表示:

Ok,我们现在开始做一个简单WCF
Application。
1.
Define a service contract
Contract顾名思义,是一种契约,它用来指定Service和Client之前消息传递的结构
2
3 namespace Contract
4 {
5 [ServiceContract(Namespace = "http://jsnhng.cnblogs.com")]
6 public interface IHello
7 {
8 [OperationContract]
9 string SayHello(string name);
10 }
11 }
2.
Implement the service contract
对上面定义的Service contract interface的实现,Service的Biz Logic都是通过这里做封装。
2
3 namespace Service
4 {
5 public class HelloService : IHello
6 {
7 public string SayHello(string name)
8 {
9 return string.Format("Hello {0}!", name);
10 }
11 }
12 }
3.
Run a basic service(host the service)
这是使用一个console application来host,其实很简单,主要对ABCB的设定都是在App.config里配置的(也可以通过代码来实现)。
App.config
2 <configuration>
3 <system.serviceModel>
4 <services>
5 <service name="Service.HelloService" behaviorConfiguration="helloBehavior">
6 <host>
7 <baseAddresses>
8 <add baseAddress="http://localhost:8080/SamplyDemo"/>
9 </baseAddresses>
10 </host>
11 <endpoint address=""
12 binding="basicHttpBinding"
13 contract="Contract.IHello" />
14 </service>
15 </services>
16 <behaviors>
17 <serviceBehaviors>
18 <behavior name="helloBehavior">
19 <serviceMetadata httpGetEnabled="True"/>
20 </behavior>
21 </serviceBehaviors>
22 </behaviors>
23 </system.serviceModel>
24 </configuration>
Program.cs(Service的代码很简单,就是通过编码方式启动Service而已)
2 using System.ServiceModel;
3 using Service;
4
5 namespace Hosting
6 {
7 class Program
8 {
9 static void Main(string[] args)
10 {
11 ServiceHost host = new ServiceHost(typeof(HelloService));
12 host.Opened += delegate { Console.WriteLine("hosting is begin to open
"); };13 host.Open();
14 Console.ReadKey();
15 }
16 }
17 }
4.
Create a client
还是使用了一个简单的console来调用Service,对WCF Service
Proxy相对应的设定也是在App.config里配置的。
2 using System.ServiceModel;
3 namespace Client
4 {
5 class HelloClient : ClientBase<IHello>, IHello
6 {
7
8 public string SayHello(string name)
9 {
10 return Channel.SayHello(name);
11 }
12 }
13 }
App.config(配置Client调用Service的具体信息,同样可以通过code方式实现)
2 <configuration>
3 <system.serviceModel>
4 <client>
5 <endpoint address="http://localhost:8080/SamplyDemo"
6 binding="basicHttpBinding"
7 contract="Contract.IHello"/>
8 </client>
9 </system.serviceModel>
10 </configuration>
Program.cs(Client调用很简单,直接就可以调用,主要对proxy调用结束后一定要注意显示关闭)
2
3 namespace Client
4 {
5 class Program
6 {
7 static void Main(string[] args)
8 {
9 using(HelloClient client=new HelloClient())
10 {
11 Console.WriteLine(client.SayHello("jsnhng"));
12 client.Close();
13 }
14 Console.ReadKey();
15 }
16 }
17 }
一个简单的WCF application就这样产生了。
浙公网安备 33010602011771号