2009-03-05 84 views
4

我有一個抽象類,我希望能夠公開到WCF,以便任何子類也能夠作爲WCF服務啓動。
這是我到目前爲止有:基於抽象類公開WCF子類

[ServiceContract(Name = "PeopleManager", Namespace = "http://localhost:8001/People")] 
[ServiceBehavior(IncludeExceptionDetailInFaults = true)] 
[DataContract(Namespace="http://localhost:8001/People")] 
[KnownType(typeof(Child))] 
public abstract class Parent 
{ 
    [OperationContract] 
    [WebInvoke(Method = "PUT", UriTemplate = "{name}/{description}")] 
    public abstract int CreatePerson(string name, string description); 

    [OperationContract] 
    [WebGet(UriTemplate = "Person/{id}")] 
    public abstract Person GetPerson(int id); 
} 

public class Child : Parent 
{ 
    public int CreatePerson(string name, string description){...} 
    public Person GetPerson(int id){...} 
} 

當試圖建立在我的代碼的服務,我用這個方法:

public static void RunService() 
{ 
    Type t = typeof(Parent); //or typeof(Child) 
    ServiceHost svcHost = new ServiceHost(t, new Uri("http://localhost:8001/People")); 
    svcHost.AddServiceEndpoint(t, new BasicHttpBinding(), "Basic"); 
    svcHost.Open(); 
} 

當使用家長作爲服務的類型,我得到
The contract name 'Parent' could not be found in the list of contracts implemented by the service 'Parent'. OR Service implementation type is an interface or abstract class and no implementation object was provided.

,並使用兒童作爲服務的類型,當我得到
The service class of type Namespace.Child both defines a ServiceContract and inherits a ServiceContract from type Namespace.Parent. Contract inheritance can only be used among interface types. If a class is marked with ServiceContractAttribute, then another service class cannot derive from it.

有沒有辦法公開Child類中的函數,所以我不必特別添加WCF屬性?

編輯
所以這

[ServiceContract(Name= "WCF_Mate", Namespace="http://localhost:8001/People")] 
    public interface IWcfClass{} 

    public abstract class Parent : IWcfClass {...} 
    public class Child : Parent, IWcfClass {...} 

與兒童啓動服務返回
The contract type Namespace.Child is not attributed with ServiceContractAttribute. In order to define a valid contract, the specified type (either contract interface or service class) must be attributed with ServiceContractAttribute.

+0

如果父實現了IWcfClass,並且Child擴展了Parent,那麼Child也不需要實現IWcfClass。 – 2009-03-06 15:20:58

回答

8

服務合同通常是一個接口,而不是一類。將您的合約放入界面,讓抽象類實現此界面,並讓我們知道當您使用Child啓動服務時會發生什麼。

編輯:好的,現在你需要修改你的RunService方法到下面。合同類型如果IWcfClass,而不是Child或Parent。

public static void RunService() 
{ 
     Type t = typeof(Child); 
     ServiceHost svcHost = new ServiceHost(t, new Uri("http://localhost:8001/People")); 
     svcHost.AddServiceEndpoint(typeof(IWcfClass), new BasicHttpBinding(), "Basic"); 
     svcHost.Open(); 
} 
+0

感謝您的輸入,但它仍然無效,除非我沒有正確實施。我在編輯中添加了對問題的修改,以便閱讀更容易。 – bju1046 2009-03-06 15:00:32