如何为wcf服务配置客户端?

时间:2009-08-23 07:20:55

标签: wcf

我正在开发一个wcf服务。 我为消息合约创建了两个dll,为服务合同接口创建了一个。 我与服务器和客户端共享这两个dll。 我没有使用AddServiceReference我使用ChannelFactory类来创建代理。 以下是我用来创建客户端代理的代码:

BasicHttpBinding binding = new BasicHttpBinding(); 
EndpointAddress endpoint = new EndpointAddress(new Uri   ("http://localhost:8989/HelloService/"));
ChannelFactory<IHello> chanFac = new ChannelFactory<IHello>(binding, endpoint);
IHello clientProxy = chanFac.CreateChannel();

现在我必须在代码中创建绑定和EndpointAddress,我希望这应该来自app.config文件,我该怎么做才能在代码中每次都不需要编写绑定和端点.... 任何帮助表示赞赏..

1 个答案:

答案 0 :(得分:8)

使用像这样的app.config(当您使用Visual Studio中的“添加服务引用”时,VS通常会自动为您创建 - 而您只需根据需要进行调整):

<configuration>
    <system.serviceModel>
        <bindings>
          <basicHttpBinding>
            <binding name="UserNameSecurity">
              <security mode="Message">
                <message clientCredentialType="UserName"/>
              </security>
            </binding>
          </basicHttpBinding>
        </bindings>
        <client>
            <endpoint address="http://localhost:8888/MyService" binding="basicHttpBinding"
                bindingConfiguration="UserNameSecurity" contract="IMyService" />
            <endpoint address="net.tcp://localhost:8484/MyService/Mex" 
                      binding="mexTcpBinding"
                      bindingConfiguration="" 
                      contract="IMetadataExchange" name="mexNetTcp" />
        </client>
    </system.serviceModel>
</configuration>

该部分及其可能的值和子部分在WCF配置中有详细记录。

或者,在VS 2008 SP1中,您可以使用“WCF服务配置编辑器” - 在“工具&gt; WCF服务配置编辑器”中查看它。

alt text

它允许您直观地定义和修改客户端配置设置。从“工具”菜单启动后,您甚至可以在解决方案资源管理器中右键单击app.config并从那里启动它(使用该app.config作为基础)。

alt text

马克