4

我有一个抽象类,我希望能够将其公开给 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();
}

当使用 Parent 作为我得到的服务类型
The contract name 'Parent' could not be found in the list of contracts implemented by the service 'Parent'.Service implementation type is an interface or abstract class and no implementation object was provided.

当使用 Child 作为我得到的服务类型时
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 {...}

使用 Child 返回启动服务
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.

4

1 回答 1

8

The service contract is usually an interface, not a class. Place your contract into an interface, have the abstract class implement this interface, and let us know what happens when you use Child to start the service.

Edit: Ok, now you need to modify your RunService method to this below. The contract type if IWcfClass, not Child or 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();
}
于 2009-03-05T21:59:09.060 回答