如何以编程方式添加WCF客户端端点?

Jef*_*yer 6 wcf

我需要我的服务来使用其他服务,我需要在代码中配置这些依赖项.我该怎么做呢?

通过以下(示例)在配置中非常简单:

   <client>
  <endpoint name="registerService"
            address="http://127.0.0.1/registration/" binding="basicHttpBinding"    
            contract="*"/>
  </client>
Run Code Online (Sandbox Code Playgroud)

但由于某些原因,找到相同的代码并不像我想象的那么容易.

Kir*_*rst 6

如果您正在使用Visual Studio生成的代理(通过"添加服务引用..."),那么您正在使用ClientBase抽象类,并且您将拥有许多允许您传入配置部分的构造函数,端点,绑定等

http://msdn.microsoft.com/en-us/library/ms576141.aspx

如果您要实例化ChannelFactory,那么您将再次使用许多构造函数.

http://msdn.microsoft.com/en-us/library/ms576132.aspx

// create bindings & endpoints
var binding = new System.ServiceModel.BasicHttpBinding();
var endpoint = new EndpointAddress("http://localhost/MyService.svc");

var factory = new ChannelFactory<IMyService>(binding, endpoint);

var channel = factory.CreateChannel();
// then call your operations...
channel.MyOperation();
Run Code Online (Sandbox Code Playgroud)