[英]WCF channelfactory with settings from the config file?
我有一個使用WCF的服務器和客戶端解決方案。 客戶端將在運行時詢問服務到活動服務器的URL的服務,並能夠使用ChannelFactory進行設置。 但是,我仍然需要使用配置文件中的所有其他WCF設置。 這是我的方法:
var clientSection = ConfigurationManager.GetSection("system.serviceModel/client") as ClientSection;
var address = string.Empty;
for(int i = 0; i < clientSection.Endpoints.Count; i++)
{
if(clientSection.Endpoints[i].Name == endpointConfigurationName)
{
var endpointAddress = new EndpointAddress(clientSection.Endpoints[i].Address.ToString());
var netHttpBinding = new NetHttpBinding(clientSection.Endpoints[i].BindingConfiguration);
var serviceEndpoint = new ServiceEndpoint(ContractDescription.GetContract(typeof(T)), netHttpBinding, endpointAddress);
var channelFactory = new ChannelFactory<T>(serviceEndpoint);
break;
}
}
問題是我得到了2個BehaviorExtensions,它們被這樣的某些端點使用。
<services>
<endpoint binding="netHttpBinding" behaviorConfiguration="protoEndpointBehavior" address="BinaryHttpProto" bindingNamespace="http://MyApp.ServiceContracts/2007/11" contract="MyApp.ServiceContracts.IMyAppClientService" />
</services>
<behaviors>
<endpointBehaviors>
<behavior name="protoEndpointBehavior">
<protobuf />
</behavior>
</endpointBehaviors>
</behaviors>
<extensions>
<behaviorExtensions>
<add name="protobuf" type="ProtoBuf.ServiceModel.ProtoBehaviorExtension, protobuf-net, Version=2.0.0.668, Culture=neutral, PublicKeyToken=257b51d87d2e4d67" />
</behaviorExtensions>
</extensions>
問題是我如何從clientSection.Endpoints讀取此內容? 並將其設置在channelFactory上? 我知道我可以像這樣手動創建:
serviceEndpoint.EndpointBehaviors.Add(new ProtoEndpointBehavior());
serviceEndpoint.EndpointBehaviors.Add(new CustomMessageInspectorBehavior());
但是,這將是一個硬編碼的靜態變量,它將應用於所有端點,我需要能夠從配置中對其進行更改。
您不需要自己創建ChannelFactory。 只需創建一個從ClientBase<T>
繼承的ClientService類。 ClientBase<T>
的構造函數接受EndpointName並自動添加與此端點關聯的行為。 ClientBase<T>
還使您可以訪問ChannelFactory<T>
並且您可以根據需要打開任意數量的通道。 您唯一需要做的就是為要使用的配置中的每個Endpoint添加一個名稱。
<endpoint binding="..." name="MyEndPoint" ... />
我不得不在代碼中創建所有內容,混合解決方案不好,在我使用大量自定義內容的情況下,則不然。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.