使用 WCF 在运行时确定 wsHttpBinding
-
23-08-2019 - |
题
我有一个使用 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"/>
解决方案
您的客户端的配置文件可能看起来是这样的:
<?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();
马克
其他提示
根据您的描述,听起来好像所有服务器都公开相同的服务合同。如果是这样,你很可能只声明多个 端点 在您的 web.config 中,并在运行时根据端点名称选择一个。
当然,您可能不想处理 WCF 配置的该部分,而宁愿只拥有一个更简单的 URL 列表并完成它。这也是完全可能的;您只需要在代码端做更多的工作来实例化客户端代理/通道对象。
不隶属于 StackOverflow