导航

WCF简介及简单应用

Posted on 2011-04-13 10:50  yjss  阅读(237)  评论(0编辑  收藏  举报

Windows Communication Foundation 

WCF是.NET 的一部分,它为快速构建可在整个 Web 和企业内进行通信的面向服务的应用程序提供了统一的编程模型。

下面我们将建立一个解决方案来说明如何建立并使用WCF服务

1、创建一个名为CalulatorService解决方案,我们要创建一个为用户提供简单计算的服务,完整案例下载

2、创建一个名为Contracts类库项目,添加ICalculator.cs接口文件,该项目为WCF服务定义了契约(就是使用服务的协定、规则)

using System.ServiceModel;

namespace Contracts
{
    // 注意: 使用“重构”菜单上的“重命名”命令,可以同时更改代码和配置文件中的接口名“IService1”。
    [ServiceContract(Name="CalculatorService",Namespace="")]
    public interface ICalculator
    {
        [OperationContract]
        double Add(double x,double y);

        [OperationContract]
        double Subtract(double x, double y);

        [OperationContract]
        double Multiply(double x, double y);

        [OperationContract]
        double Divide(double x, double y);

        // TODO: 在此添加您的服务操作
    }

    // 使用下面示例中说明的数据协定将复合类型添加到服务操作
}

3、创建一个名为Services类库项目,添加CalculatorService.cs类文件,该文件实现ICalculator

using Contracts;

namespace Services
{
    // 注意: 使用“重构”菜单上的“重命名”命令,可以同时更改代码和配置文件中的类名“Service1”。
    public class CalculatorService :ICalculator
    {
        public double Add(double x, double y)
        {
            return x + y;
        }

        public double Subtract(double x, double y)
        {
            return x - y;
        }

        public double Multiply(double x, double y)
        {
            return x * y;
        }

        public double Divide(double x, double y)
        {
            return x / y;
        }
    }
}

4、为WCF提供宿主运行环境,创建名为Hosting控制台程序,以下提供了通过代码创建服务和配置文件创建的方式

using System;
using System.ServiceModel;
using System.ServiceModel.Description;
using Contracts;
using Services;

namespace Hosting
{
    class Program
    {
        static void Main(string[] args)
        {
            C_Main(null);
            return;
            using (ServiceHost host = new ServiceHost(typeof(CalculatorService)))
            {
                host.AddServiceEndpoint(typeof(ICalculator), new WSHttpBinding(), "http://127.0.0.1:8888/CalculatorService");
                if (host.Description.Behaviors.Find<ServiceMetadataBehavior>() == null)
                {
                    ServiceMetadataBehavior behavior = new ServiceMetadataBehavior();
                    behavior.HttpGetEnabled = true;
                    behavior.HttpGetUrl = new Uri("http://127.0.0.1:8888/CalculatorService/metadata");
                    host.Description.Behaviors.Add(behavior);
                }
                host.Opened += delegate
                {
                    Console.WriteLine("服务已启动,按任意键退出!");
                };
                host.Open();
                Console.Read();
            }
        }
        static void C_Main(string[] args)
        {
            using (ServiceHost host = new ServiceHost(typeof(CalculatorService)))
            {
                host.Opened += delegate
                {
                    Console.WriteLine("服务已启动,按任意键退出!");
                };
                host.Open();
                Console.Read();
            }
        }
    }
}

配置文件设置

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name="metadataBehavior">
<serviceMetadata httpGetEnabled="true"
httpGetUrl
="http://127.0.0.1:8888/CalculatorService/metadata"/>
</behavior>
</serviceBehaviors>
</behaviors>
<services>
<service behaviorConfiguration="metadataBehavior" name="Services.CalculatorService">
<endpoint address="http://127.0.0.1:8888/CalculatorService"
      binding
="wsHttpBinding" contract="Contracts.ICalculator"/>
</service>
</services>
</system.serviceModel>
</configuration>

5、将服务寄宿在IIS中,创建名为IISHosting的WCF服务WEB程序,添加名为CalculatorService.svc服务文件

<%@ ServiceHost Language="C#" Debug="true" Service="Services.CalculatorService" %>

配置文件

<?xml version="1.0" encoding="utf-8"?>
<configuration>

<system.web>
<compilation debug="false" targetFramework="4.0" />
</system.web>
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name="metadataBehavior">
<!-- 为避免泄漏元数据信息,请在部署前将以下值设置为 false 并删除上面的元数据终结点 -->
<serviceMetadata httpGetEnabled="true"/>
<!-- 要接收故障异常详细信息以进行调试,请将以下值设置为 true。在部署前设置为 false 以避免泄漏异常信息-->
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
</behaviors>
<!--<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />-->
<services>
<service behaviorConfiguration="metadataBehavior" name="Services.CalculatorService">
<endpoint binding="wsHttpBinding" contract="Contracts.ICalculator"/>
</service>
</services>
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>

</configuration>

6、在客户端调用,创建名为Client和控制台程序,以下WCF服务提供了两种调用方式,第一种方式要为项目添加服务引用,第二种要添加对Contracts项目的引用

using System;
using System.ServiceModel;
using Client.CalculatorServices;
using Contracts;

namespace Client
{
    class Program
    {
        static void Main(string[] args)
        {
            IIS_Main(null);
            return;
            CF_Main(null);
            return;
            using (CalculatorServiceClient proxy = new CalculatorServiceClient())
            {
                Console.WriteLine(proxy.Add(1,2));
                Console.WriteLine(proxy.Subtract(1, 2));
                Console.WriteLine(proxy.Multiply(1, 2));
                Console.WriteLine(proxy.Divide(1, 2));
                Console.Read();
            }
        }
        static void CF_Main(string[] args)
        {
            using (ChannelFactory<ICalculator> channelFactory = new ChannelFactory<ICalculator>(
                new WSHttpBinding(), "http://127.0.0.1:8888/CalculatorService"))
            {
                ICalculator proxy = channelFactory.CreateChannel();
                Console.WriteLine(proxy.Add(1, 2));
                Console.WriteLine(proxy.Subtract(1, 2));
                Console.WriteLine(proxy.Multiply(1, 2));
                Console.WriteLine(proxy.Divide(1, 2));
                Console.Read();
            }
        }
        static void IIS_Main(string[] args)
        {
            using (ChannelFactory<ICalculator> channelFactory = new ChannelFactory<ICalculator>(
                new WSHttpBinding(), "http://127.0.0.1:2881/IISHosting/CalculatorService.svc"))
            {
                ICalculator proxy = channelFactory.CreateChannel();
                Console.WriteLine(proxy.Add(1, 2));
                Console.WriteLine(proxy.Subtract(1, 2));
                Console.WriteLine(proxy.Multiply(1, 2));
                Console.WriteLine(proxy.Divide(1, 2));
                Console.Read();
            }
        }
    }
}