我有一个抽象类,我希望能够向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.
答案 0 :(得分: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();
}