WCF 学习系列之二:WCF 入门级 使用教程 上

WCF 入门级 使用教程 上
2009-02-17 16:54

开发环境:vs2008英文版(SP1) + IIS + Windows2003

整个解决方案有4个项目
01.WCF ---Class Libary项目,用于生成WCF所需的类/接口文件
02.BLL ---Class LIbary项目,演示用的业务逻辑层(仅做分层演示用,无实际意义)
03.WEB ---Web Application,WCF服务将发布在这个项目中(即本例是把WCF宿主在IIS里)
04.Client--Console Application,命令行程序,用于演示调用WCF的客户端程序

项目引用关系:
01.WCF ---独立项目,无引用
02.BLL ---引用WCF,即业务逻辑层,引用Wcf
03.web ---引用BLL,即Web UI层引用BLL
04.Client --独立项目,无引用

步骤:
1.打开vs2008,File-->new project-->Visual C#/Windows-->Class Libary,命名为01_WCF


2.WCF项目上右击,Add-->New Item-->WCF Service ,命名为CalculateService.cs,确认后,系统会同时生成一个ICalculateService.cs的接口文件

ICalculateService.cs的内容如下(本例中,仅写了二个示例方案,Add与Sub,用于实现数字的加减):


1using System;
2using System.Collections.Generic;
3using System.Linq;
4using System.Runtime.Serialization;
5using System.ServiceModel;
6using System.Text;
7
8namespace WCF
9{
10    // NOTE: If you change the interface name "ICalculateService" here, you must also update the reference to "ICalculateService" in App.config.
11     [ServiceContract]
12    public interface ICalculateService
13    {
14         [OperationContract]
15        double Add(double x, double y);
16
17         [OperationContract]
18        double Sub(double x, double y);       
19     }
20}

这里可以看出,除了类前面加了[ServiceContract],以及方法签名前加了[OperationContract],其它跟普通的接口文件完全一样。这部分也称为WCF的契约
再来看CalculateService.cs,即实现契约的部分


1using System;
2using System.Collections.Generic;
3using System.Linq;
4using System.Runtime.Serialization;
5using System.ServiceModel;
6using System.Text;
7
8namespace WCF
9{
10    // NOTE: If you change the class name "CalculateService" here, you must also update the reference to "CalculateService" in App.config.
11    public class CalculateService : ICalculateService
12    {
13        public double Add(double x, double y)
14        {
15            return x + y;
16         }
17
18        public double Sub(double x, double y)
19        {
20            return x - y;
21         }       
22     }
23}

这个类实现了刚才的ICalculateService接口,其它与普通类文件完全一样

build一下,如果没错的话,wcf这个项目就算完工了

3.解决方案上右击,add-->new Project-->class Libary 命名为BLL,即业务逻辑层,然后在BLL项目的References上右击-->add References-->Projects-->选择01_WCF项目,完成对项目WCF的引用

4.把BLL中默认的Class1.cs删除,新建一个Test.Cs,内容如下:


1using System;
2using System.Collections.Generic;
3using System.Linq;
4using System.Text;
5
6namespace BLL
7{
8    public  class Test
9    {
10        public string HelloWorld()
11        {
12            return "Hello World!";
13         }
14
15        public double Add(double x, double y)
16        {
17            return new WCF.CalculateService().Add(x, y);
18         }
19     }
20}

这里仅做了一个示例,写了一个Add方法,用来调用WCF.CalculateService中的Add方法,到目前为止,可以看出,这跟普通项目的引用,以及普通类的引用没有任何区别,Build一下,如果没有问题的话,BLL项目也告一段落了

5.解决方案右击,add-->new project-->Asp.net Web Applicatin或Asp.net 3.5 Extenstions Web Application都可以,命名为03_WEB,同样添加对BLL项目的引用

原文地址:https://www.cnblogs.com/millen/p/1506592.html