2011-02-24 85 views
3

我想將端點配置存儲在.config文件中,但能夠在運行時修改基址。 EG:這些都是我的端點定義中的app.config:從客戶端獲取/修改地址端點配置

<endpoint address="net.tcp://BASEURI:1001/FooService/" 
      binding="netTcpBinding" bindingConfiguration="NetTcpBinding_Common" 
      contract="ServiceContracts.MyService" 
      name="FooService" /> 

<endpoint address="net.tcp://BASEURI:1002/BarService/" 
      binding="netTcpBinding" bindingConfiguration="NetTcpBinding_Special" 
      contract="ServiceContracts.MyService" 
      name="BarService" /> 

每個服務都使用相同的合同(ServiceContracts.MyService),但住在不同的端口,不同的路徑,有時不同的綁定配置上。

我希望能夠以編程方式提取地址「的net.tcp://基本URI/FooService接口/」,將「基本URI」與服務器的地址,然後當客戶端通過這個作爲地址的DuplexChannelFactory連接已創建。 EG:

string ServiceToUse = "FooService"; 

var endpointConfig = SomeFunctionThatGetsTheConfig(ServiceToUse); 
string trueAddress = endpointConfig.Address.Replace("BASEURI", "192.168.0.1"); 
DuplexChannelFactory<FooService> client = 
    new DuplexChannelFactory<FooService>(ServiceToUse, new EndpointAddress(trueAddress)); 

我知道,客戶終端不支持< baseAddress的服務端點>功能,但我的目的是要變通,不知怎的讓我不必知道是什麼其餘的URI或綁定是。

注意:我沒有使用Proxy類,我直接使用DuplexChannelFactory。

回答

5

您可以在自己的ChannelFactory做到這一點很容易,如:

ChannelFactory<IFoo> cf = new ChannelFactory<IFoo>("EndpointConfigName"); 
string address = cf.Endpoint.Address.Uri.ToString(); 
address = address.Replace("BASEURI", "192.168.0.1"); 
cf.Endpoint.Address = new EndpointAddress(address); 

那麼,你必須DuplexChannelFactory,但這個想法是一樣的。

+0

完美,第一次工作。非常感謝。編輯:WCF似乎轉換服務器部分ToLower,所以你必須匹配「baseuri」而不是「BASEURI」。否則,它工作正常。 – 2011-02-24 19:14:11

0

執行IEndpointBehavior並在添加時更改URL。

您需要更改ServiceEndpointApplyClientBehavior

void ApplyClientBehavior(
    ServiceEndpoint endpoint, 
    ClientRuntime clientRuntime 
) 
{ 
    endpoint.Address = ... 
} 
+0

我在哪裏實現IEndpointBehavior?沒有使用代理類,只有DuplexChannel。 – 2011-02-24 18:09:51

+0

看看這裏的例子:http://msdn.microsoft.com/en-us/library/ms730137.aspx – Aliostad 2011-02-24 18:20:05

+0

雖然我設法實現了IEndpointBehavior,並且我的ApplyCientBehavior方法在通道創建時調用,但爲時已晚更改端點地址。該更改不會生效。 – 2011-02-24 19:07:40