使用WCF在运行时确定wsHttpBinding

时间:2009-05-22 02:02:43

标签: wcf wcf-binding wcf-client

我有一个使用WCF和wsHttpBindings公开Web服务的Web应用程序。可以将应用程序放在不同的机器和不同的URL上。这意味着每个WCF服务位置都不同。

我正在构建一个Windows服务,它将引用每个应用程序并执行任务。每个任务都需要在Web应用程序上调用服务。我知道绑定都是在app.config中设置的,但有一种更简单的方法可以动态调用服务,或者我将如何构建app.config?

<webApplication WebServiceUrl="http://location1.com/LunarChartRestService.svc" />
<webApplication WebServiceUrl="http://location2.com/LunarChartRestService.svc"/>

2 个答案:

答案 0 :(得分:1)

您客户的配置文件可能如下所示:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <system.serviceModel>
    <client>
      <endpoint name="Endpoint1"
                address="http://location1.com/LunarChartRestService.svc"
                binding="wsHttpBinding"
                contract="(whatever-your-contract-is)" />
      <endpoint name="Endpoint2"
                address="http://location2.com/LunarChartRestService.svc"
                binding="wsHttpBinding"
                contract="(whatever-your-contract-is)" />
      <endpoint name="Endpoint3"
                address="http://location3.com/LunarChartRestService.svc"
                binding="wsHttpBinding"
                contract="(whatever-your-contract-is)" />
    </client>
  </system.serviceModel>
</configuration>

然后在代码中,您可以根据其名称创建此类端点(客户端代理),因此您可以选择所需的任何位置。没有什么可以阻止你创建多个客户端代理!因此,您可以使用多个客户端代理连接到多个服务器端点,没问题。

或者,您当然也可以在代码中创建“WsHttpBinding”和“EndpointAddress”的实例,并设置必要的属性(如果有的话),然后使用这些现成的对象调用客户端代理的构造函数,从而覆盖整个app.config马戏团并创建你认为需要的东西:

EndpointAddress epa = 
    new EndpointAddress(new Uri("http://location1.com/LunarChartRestService.svc"));
WSHttpBinding binding = new WSHttpBinding();

马克

答案 1 :(得分:0)

从您的描述中,听起来好像所有服务器都暴露了相同的服务合同。如果是这样,您可以在web.config中声明多个endpoints,并根据端点名称在运行时选择一个。{/ p>

当然,您可能希望不处理WCF配置的那一部分,而只是想拥有一个更简单的URL列表并完成它。这也是完全可能的;你只需要在代码端做更多的工作来实例化客户端代理/通道对象。