2009-04-17 42 views
0

我試圖從使用WCF的另一個應用程序中獲取對象。使用內置類,它可以正常工作,但是當我試圖從WCF操作中返回一個自定義的接口類型時,我會遇到probems。在WCF服務中公開自定義複雜接口類型的問題

無論我將接口分別包含在兩個應用程序中,還是將其指定爲共享程序集,我都會得到相同的結果:CommunicationException帶有消息「管道發生錯誤:無法識別的錯誤109」。

界面看起來是這樣的:

[ServiceContract] 
public interface IBase { 
    int IntTest { 
     [OperationContract] 
     get; 
    } 
    String StringTest { 
     [OperationContract] 
     get; 
    } 
    IOther OtherTest { 
     [OperationContract] 
     get; 
    } 
} 

[ServiceContract] 
public interface IOther { 
    String StringTest { 
     [OperationContract] 
     get; 
    } 
} 

我的服務器看起來是這樣的:

public partial class MainWindow : Window { 
    private Base fb; 
    private ServiceHost host; 

    public MainWindow() { 
     InitializeComponent(); 
     fb = new Base(); 
     host = new ServiceHost(fb, new Uri[] { new Uri("net.pipe://localhost") }); 
     host.AddServiceEndpoint(typeof(IBase), new NetNamedPipeBinding(), 
      "PipeReverse"); 
     host.Open(); 
    } 

    private void Window_Closing(object sender, CancelEventArgs e) { 
     host.Close(); 
    } 
} 

這裏是我的接口的實現:

[Serializable] 
[ServiceBehavior(InstanceContextMode=InstanceContextMode.Single)] 
public class Base : MarshalByRefObject, IBase { 
    public int IntTest { 
     get { return 4; } 
    } 

    public string StringTest { 
     get { return "A string from Base"; } 
    } 

    public IOther OtherTest { 
     get { return new Other(); } 
    } 
} 

[Serializable] 
[DataContract] 
public class Other : MarshalByRefObject, IOther { 
    [DataMember] 
    public string StringTest { 
     get { return "A string from Other"; } 
    } 

} 

客戶端看起來像這個:

public partial class Form1 : Form { 

    IBase obj; 

    public Form1() { 
     InitializeComponent(); 
     ChannelFactory<IBase> pipeFactory = new ChannelFactory<IBase>(
      new NetNamedPipeBinding(), new EndpointAddress(
      "net.pipe://localhost/PipeReverse")); 

     obj = pipeFactory.CreateChannel(); 
    } 


    private void button2_Click(object sender, EventArgs e) { 

     Console.WriteLine("Returns: " + obj.StringTest + " " + 
      obj.StringTest.Length); 
     Console.WriteLine("Returns: " + obj.IntTest); 
     Console.WriteLine(obj.OtherTest); 

    } 
} 

一切工作一樣,除了這條線的魅力:

Console.WriteLine(obj.OtherTest); 

它給我與消息的CommunicationException「有錯誤從管道讀取:無法識別錯誤109」。據我所知,這是一個由於故障狀態而損壞的管道,但我無法弄清楚爲什麼,或者更重要的是如何解決它。有任何想法嗎?

我沒有配置文件,因爲everthing是在上面的代碼中完成的,所以我不知道如何打開跟蹤,否則我也會包含它。

+0

我在機器上運行這段代碼。雖然IntTest和StringTest方法沒有返回錯誤,但也沒有數據。其他的東西可能是錯的。 – 2009-04-18 15:49:15

回答

2

返回的屬性其他測試需要是具體類型而不是接口,否則序列化將不起作用。

+0

就是這樣!謝謝。實際上,這意味着我必須在共享程序集中擁有業務對象。我希望能夠複製界面,但我想這必須做。再次感謝您的幫助。 – Farawin 2009-04-20 07:37:16

0

這通常是一個序列化錯誤。查看[KnownType]屬性。測試這個最簡單的方法是直接調用DataContractSerializer。您可以使用其WriteObject和ReadObject方法來獲取真正的序列化錯誤。您也可以檢查流(FileStream通常)以確保您正確輸入序列化。