代码改变世界

WCF步步为营(三):使用配置文件改变使用服务的方式

2008-07-03 10:57  敏捷的水  阅读(830)  评论(0编辑  收藏  举报

1. 打开上节的解决方案,为JackWangServiceClient工程添加一个App.config文件

image

2. 修改App.config的文件如下

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

<configuration>

  <system.serviceModel>

    <client>     

        <endpoint  name="MyEndPoint" binding="basicHttpBinding" 

          contract="JackWangServiceClient.ICalc" address="http://localhost:9000/Add" />         

    </client

  </system.serviceModel>

</configuration>

 

3. 修改Program.cs文件,绿色是注释掉的部分,由于使用配置文件,我们需要使用ChannelFactory<T>的实例。

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.ServiceModel;

namespace JackWangServiceClient

{

    [ServiceContract]

    public interface ICalc

    {

        [OperationContract]

        long Add(int a, int b);

    }

    class Program

    {

        static void Main(string[] args)

        {

            //ICalc proxy = ChannelFactory<ICalc>.CreateChannel(new BasicHttpBinding(),

            //    new EndpointAddress("http://localhost:9000/Add"));

            ChannelFactory<ICalc> channelFactory = new ChannelFactory<ICalc>("MyEndPoint");

 

            ICalc proxy = channelFactory.CreateChannel();

            long result = proxy.Add(50, 60);

            Console.Out.WriteLine("result from server is:" + result);

            Console.ReadLine();

        }

    }

}

 

这样,当服务器修改配置方式时,我们不用改变代码,直接修改配置文件即可。