【问题标题】:WCF Generic ClassWCF 泛型类
【发布时间】:2012-01-25 11:55:08
【问题描述】:

这如何作为 WCF 服务工作?

public class BusinessObject<T> where T : IEntity
{
    public T Entity { get; set; }

    public BusinessObject(T entity)
    {
        this.Entity = entity;
    }
}

public interface IEntity { }

public class Student : IEntity
{
    public int StudentID { get; set; }
    public string Name { get; set; }
}

我想在 WCF 服务中公开 BusinessObject 类和所有继承 IEntity 接口的类。

我的代码在 C#、.NET Framework 4.0 中,在 Visual Studio 2010 Pro 中构建。

【问题讨论】:

    标签: c# wcf generics .net-4.0


    【解决方案1】:

    在通过 WCF 向客户端公开 BusinessObject 时,您必须使用封闭的泛型类型来做到这一点。

    [DataContract]
    public class BusinessObject<T> where T : IEntity
    {
        [DataMember]
        public T Entity { get; set; }
    
        public BusinessObject(T entity)
        {
            this.Entity = entity;
        }
    }  
    
    [ServiceContract]
    interface IMyContract {
    [OperationContract]
    BusinessObject<Student> GetStudent(...) // must be closed generic
    }
    

    【讨论】:

    • 但是student并不是T类型的唯一类型。我有很多实体类。
    • 我现在明白了,但是我需要将 DataContract 和 DataMember 属性添加到我的所有实体类吗?
    • WCF 的面向服务的性质不允许这样做。从客户的角度思考。到客户打电话时,合同应该是众所周知的。
    • 是的,你需要用 DataMember 属性来装饰它们。
    【解决方案2】:

    KnownType 属性是一种确保将合同的类型数据添加到 wsdl 元数据的方法。这仅适用于类,不适用于接口。接口不能存储数据,并且不是所有语言都能普遍理解的,因此它不能真正通过 wcf 公开。看这里-http://social.msdn.microsoft.com/forums/en-US/wcf/thread/7e0dd196-263c-4304-a4e7-111e1d5cb480

    【讨论】:

      【解决方案3】:

      您需要向主机注册 DataContractResolver 行为,以便 WCF 可以动态(反)序列化未知类型。在此处查看更多信息:

      http://msdn.microsoft.com/en-us/library/ee358759.aspx

      也就是说,类型仍然需要是封闭的泛型类型,尽管是一个通用的基类 AFAIK。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-05-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多