2011-06-02 75 views
1

我需要有一個通用的服務合同,但如果我這樣做,我收到此錯誤:一般服務合同

[ServiceContract] 
public interface IService<T> where T : MyClass 
{ 
    [OperationContract] 
    void DoWork(); 
} 

合同名稱「XY」不能由執行合同的名單中找到服務'z.t'。

+0

是否更改了錯誤消息? – Nix 2011-06-02 15:48:17

+0

是的,但概念是相同的。謝謝。 – user758977 2011-06-02 15:50:19

+4

我不認爲服務契約可以是通用的。 – 2011-06-02 15:50:54

回答

0

只要你爲你的界面使用了一個封閉的泛型,它就可以工作 - 見下文。你不能做的是有一個開放的通用作爲契約類型。

public class StackOverflow_6216858_751090 
{ 
    public class MyClass { } 
    [ServiceContract] 
    public interface ITest<T> where T : MyClass 
    { 
     [OperationContract] 
     string Echo(string text); 
    } 
    public class Service : ITest<MyClass> 
    { 
     public string Echo(string text) 
     { 
      return text; 
     } 
    } 
    static Binding GetBinding() 
    { 
     BasicHttpBinding result = new BasicHttpBinding(); 
     //Change binding settings here 
     return result; 
    } 
    public static void Test() 
    { 
     string baseAddress = "http://" + Environment.MachineName + ":8000/Service"; 
     ServiceHost host = new ServiceHost(typeof(Service), new Uri(baseAddress)); 
     host.AddServiceEndpoint(typeof(ITest<MyClass>), GetBinding(), ""); 
     host.Open(); 
     Console.WriteLine("Host opened"); 

     ChannelFactory<ITest<MyClass>> factory = new ChannelFactory<ITest<MyClass>>(GetBinding(), new EndpointAddress(baseAddress)); 
     ITest<MyClass> proxy = factory.CreateChannel(); 
     Console.WriteLine(proxy.Echo("Hello")); 

     ((IClientChannel)proxy).Close(); 
     factory.Close(); 

     Console.Write("Press ENTER to close the host"); 
     Console.ReadLine(); 
     host.Close(); 
    } 
} 
+0

注意:http://stackoverflow.com/questions/1735035/c-sharp-generics-open-and-closed-constructed-types – 2013-05-16 02:35:11

0

您的服務合同不可互操作。通過WSDL公開類似的泛型是不可能的。

看一看這篇文章(link)可能的解決方法。

+0

如果所有連接到此服務的客戶端都是.Net,會怎麼樣?其他人關心互操作嗎?這可能是內部應用程序,因此不需要互操作。 IMO錯誤的答案 – War 2014-08-14 12:19:09

0

如果您在客戶端使用servicereference,泛型將失敗。

使用在客戶端與通用如下:

var myBinding = new BasicHttpBinding(); 
var myEndpoint = new EndpointAddress(""); 
var myChannelFactory = new ChannelFactory<IService>(myBinding, myEndpoint); 
IService gks = myChannelFactory.CreateChannel();