在wcf客户端中动态设置端点地址(使用net tcp绑定)

Jen*_*Jen 3 .net wcf wcf-binding nettcpbinding

所以我对WCF并不过分熟悉,而且我用Google搜索的所有内容都没有帮助我如何实现我的需求.对不起,如果这是一个愚蠢的问题:)

基本上有一个服务器应用程序,其中包含使用WCF(net tcp绑定)公开的服务.我写了一个新的控制台应用程序,我需要调用该服务.所以我可以通过为我们拥有的代理项目添加一个dll并添加一堆配置文件(例如WCFClientBindings,WCFClientEndPoints)来实现这一点.如果我使用定义的终点,那么我可以调用这样的代码:

using (var partyProxy = new PartyControllerProxy())
            {
                // execute server method 
                partyProfile = partyProxy.GetLatestPartyProfile(context, parsedParameters.PartyId);
            }
Run Code Online (Sandbox Code Playgroud)

但是应用程序应该能够调用作为命令行参数传入的主机名.

因此,虽然我的应用程序使用定义的端点:

<client>
  <endpoint
  name="IPartyControllerEndpoint"
  address="net.tcp://localhost:46000/ServiceInterface/PartyController.svc"
  binding="customBinding" bindingConfiguration="DefaultNetTcpBindingConfiguration"
  contract="CompanyA.Service.Product.Core.Contracts.IPartyController"
  behaviorConfiguration="DefaultEndpointBehavior">
  </endpoint>
</client>
Run Code Online (Sandbox Code Playgroud)

我需要能够将localhost主机名更新为其他东西.我希望安全不会让我失望:)

我见过的例子似乎是通过传递"动态"绑定和地址来实例化客户端/代理,但我们的代理类不接受这些.在调用"代理"类之前,有没有办法更新端点的地址(在运行时)?我见过的唯一其他例子涉及实例化一个新的ServiceHost - 但这对客户来说听起来不太合适:)

谢谢!

编辑 -好的,这里的语法似乎很好用.这与我接受的答案有点不同,但这种方法是要走的路:)

using (ChannelFactory<IPartyController> factory = new ChannelFactory<IPartyController>("IPartyControllerEndpoint"))
        {
            EndpointAddress address = new EndpointAddress(String.Format("net.tcp://{0}/ServiceInterface/PartyController.svc", parsedParameters.HostName));
            IPartyController channel = factory.CreateChannel(address);

            partyProfile = channel.GetLatestPartyProfile(context, parsedParameters.PartyId);
            ((IClientChannel)channel).Close();
        }
Run Code Online (Sandbox Code Playgroud)

Bra*_*rad 5

您可以创建一个ChannelFactory.

与标准客户端一起,WCF WSDL还将为客户端提供接口类.

EndpointAddress address = new EndpointAddress("http://dynamic.address.here");
        using (ChannelFactory<IPartyControllerChannel> factory = new ChannelFactory<IPartyControllerChannel>("IPartyControllerEndpoint", address))
        {

            using (IPartyControllerChannel channel = factory.CreateChannel())
            {
                channel.GetLatestPartyProfile(context, parsedParameters.PartyId);
            }
        }
Run Code Online (Sandbox Code Playgroud)