WCF Generic Class

2019-07-20 16:48发布

问题:

How can this work as a WCF Service?

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; }
}

I want to expose the BusinessObject <T> class and the all the class that inherits the IEntity interface in the WCF Service.

My code is in C#, .NET Framework 4.0, build in Visual Studio 2010 Pro.

回答1:

While exposing BusinessObject to the clients via WCF, you must do that by using closed generic type.

[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
}


回答2:

KnownType attribute is a way to ensure that the type data for the contract is added to the wsdl metadata. This only works for classes it will not work for an interface. An interface cant store data and is not univerally understood by all languages out there so its not really exposable over wcf. See this here- http://social.msdn.microsoft.com/forums/en-US/wcf/thread/7e0dd196-263c-4304-a4e7-111e1d5cb480



回答3:

You need to register a DataContractResolver behavior with your host so WCF can (de)serialize as yet unknown types dynamically. See more information here:

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

That said, the type still needs to be closed generic type, albeit a common base class AFAIK.