2015-05-05 27 views
2

我正在以編程方式創建一個命名管道WCF服務和客戶端。爲什麼「在配置元素集合中找不到與鍵匹配的元素」?

服務代碼執行:

serviceHost = new ServiceHost(typeof(CFCAccessPointService), new Uri(Names.Address)); 
serviceHost.AddServiceEndpoint(typeof (ICfcAccessPoint), new NetNamedPipeBinding(Names.Binding), Names.Contract); 
serviceHost.Open(); 

客戶端代碼:

var ctx = new InstanceContext(new StatusHandler()); 
s_proxy = new DuplexChannelFactory<ICfcAccessPoint>(ctx, new NetNamedPipeBinding(Names.Binding), new EndpointAddress(Names.Address)); 

public static class Names 
{ 
    public const string Address = "net.pipe://localhost/CFC/Plugins/GuestAccessService"; 
    public const string Binding = "netNamedPipeBinding_ICfcAccessPoint"; 
    public const string Contract = "GuestAccessClientServerInterface.ICfcAccessPoint"; 
} 

,以確保客戶端和服務保持不變。

但是,如果我刪除Names.Binding,以便沒有指定綁定配置,則會出現在端點上找不到偵聽器的錯誤。如果我包含它,我會得到「在配置元素集合中找不到與密鑰匹配的元素」...

我沒有使用.config文件。

還缺什麼?

回答

1

無論如何,綁定都很好,事實上根本就不需要任何參數。

問題在於合同。當我改成代碼:

public static class Names 
{ 
    public const string Address = "net.pipe://localhost/CFC/Plugins/GuestAccessService/"; 
    public const string Binding = ""; 
    public const string Contract = "CfcAccessPoint"; 
} 

,並在服務端:

this.serviceHost.AddServiceEndpoint(typeof(ICfcAccessPoint), new NetNamedPipeBinding(), Names.Contract); 

,並在客戶端:

var ctx = new InstanceContext(this); 
proxy = new DuplexChannelFactory<ICfcAccessPoint>(ctx, new NetNamedPipeBinding(), new EndpointAddress(Names.Address) + Names.Contract); 

那麼事情的罰款。該服務只是命名管道;客戶端將地址添加到管道名稱。

Voilá!

1

這意味着在配置文件中沒有與該名稱的綁定。既然你已經聲明你沒有使用配置文件,這並不奇怪。在Web.config或app.config中配置WCF端點是不可能的嗎?這只是我的看法,但是當我需要對服務的各個屬性進行隨機調整時,我發現配置方法更加靈活。

無論哪種方式,MSDN docsNetNamedPipeBinding(string)構造函數,簽名是這樣的:

public NetNamedPipeBinding(
    string configurationName 
) 

這意味着,只有這樣,才能實例化此構造一個NetNamedPipeBinding需要一個有名稱的字符串匹配結合存在於你的web.config或app.config文件中。這將是這個樣子:

<system.serviceModel> 
    <bindings> 
     <netNamedPipeBinding> 
      <binding name="netNamedPipeBinding_ICfcAccessPoint" /> 
     <netNamedPipeBinding> 
    </bindings> 
</system.serviceModel> 

您可能正在尋找它看起來更像這樣的構造:

public NetNamedPipeBinding(
    NetNamedPipeSecurityMode securityMode 
) 

這裏是MSDN鏈接。

使用此構造方法,您的服務主機代碼將looke更多這樣的:

serviceHost = new ServiceHost(typeof(CFCAccessPointService), new Uri(Names.Address)); 
serviceHost.AddServiceEndpoint(typeof (ICfcAccessPoint), new NetNamedPipeBinding(NetNamedPipeSecurityMode.None), Names.Contract); 
serviceHost.Open(); 

而且這樣你的客戶端代碼:

var ctx = new InstanceContext(new StatusHandler()); 
s_proxy = new DuplexChannelFactory<ICfcAccessPoint>(ctx, new NetNamedPipeBinding(NetNamedPipeSecurityMode.None), new EndpointAddress(Names.Address)); 

這應該避免對配置文件的需要。

+0

對不起,但沒有任何建議工作。當我修改代碼來設置安全模式時,我得到了無聽者錯誤。添加配置文件完全沒有區別。 – shipr

相關問題