我有一个抽象类,我希望能够向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作为我得到的服务类型时 在服务'Parent'实现的合同列表中找不到合同名称'Parent'。 要么 服务实现类型是一个接口或抽象类,没有提供任何实现对象。

当使用Child作为我得到的服务类型时 Namespace.Child类型的服务类都定义了一个ServiceContract,并从Namespace.Parent类型继承了ServiceContract。合同继承只能在接口类型中使用。如果一个类用ServiceContractAttribute标记,那么另一个服务类不能从它派生。

有没有办法公开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返回
启动服务 合同类型Namespace.Child未归属于ServiceContractAttribute。为了定义有效的合同,指定的类型(合同接口或服务类)必须使用ServiceContractAttribute来归属。

有帮助吗?

解决方案

服务合同通常是一个接口,而不是一个类。将您的合同放入一个接口,让抽象类实现此接口,并告诉我们当您使用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();
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top