从合同中访问端点配置

时间:2014-08-15 15:46:07

标签: c# wcf portable-class-library channelfactory

我在PCL中使用ChannelFactory来使用WCF服务。我的配置看起来像这样:

<client>
    <endpoint 
        address="https://www.site.com/ProductService.svc" 
        binding="customBinding" 
        contract="Interface.IProductService" 
    ...

使用它的代码如下所示:

Binding binding = new BasicHttpBinding(BasicHttpSecurityMode.TransportCredentialOnly);

ChannelFactory<Interface.IProductService> cf = new 
     ChannelFactory<Interface.IProductService>();
Interface.IProductService tc = cf.CreateChannel();
tc.GetProduct(1);

我遇到的问题是我被要求在ChannelFactory构造函数中提供端点名称。是否可以让ChannelFactory仅从合同中推断出正确的终点?

1 个答案:

答案 0 :(得分:0)

除非我误解了你的问题,否则没有。端点是ABC的组合,而不仅仅是合同,您可能有不同的端点用于不同的协议。但是,除非你有一些其他的复杂因素没有命名,否则给端点提供合同的名称是非常简单的,只需按名称拉出它:

   <client>
        <endpoint name="IProductService"
            address="https://www.site.com/ProductService.svc" 
            binding="customBinding" 
            contract="Interface.IProductService" 
        ...

然后:

Binding binding = new BasicHttpBinding(BasicHttpSecurityMode.TransportCredentialOnly);

string typeName = typeof(Interface.IProductService).Name;
ChannelFactory<Interface.IProductService> cf = new 
     ChannelFactory<Interface.IProductService>(typeName);
Interface.IProductService tc = cf.CreateChannel();
tc.GetProduct(1);

当然,如果你为很多服务做这件事,那就不实用了。但是,如果你以相同的系统方式进行,我发现从基础接口派生这些接口很有用,并将整个ChannelFactory管理问题作为中间人ChannelFactory<T> where T : IMyBaseContractInterface处理。

相关问题