2009-03-05 82 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