Sunday, May 20, 2012

WCF: Serialization and Generics

Recently, I have been spending some time blogging about serialization.  This is partially in an effort to go back over some of the basics prior to starting on WCF and P2P in a week or so.  Today, I am continuing the serialization subject by taking a closer look at generics in regards to serialization.

This is actually a popular subject for a lot of newcomers to WCF.  Many developers who are fond of generics will create a service that exposes some generic method.  When they finally get ready to fire up the service and give it a trial run, they are quickly disappointed to discover that it doesn't work as expected.

So, what's the deal?

WCF does not support the use of generic methods for service operation.  In other words, only concrete types can be used for service operations.  Open generic types cannot be used.  Now, it is important to clarify this is not a limitation of WCF.  Rather, it is a limitation of WSDL, which is used to expose service metadata to consumers.  There is no construct within WSDL to define a generic type.  Generally speaking, I agree with this behavior 
since it decreases the coupling between a client and service. 

Although generic methods are not supported, it is possible to expose generic objects for the purpose of exchanging data.  However, there are some limitations.  Let's take a closer look:

Bounded Generics

In his book Programming WCF Services , Juval Lowy points out that it is possible to use "bounded generics."  This is sometimes referred to as closed generics.  Basically, it refers to defining a generic class for your data contract, but it is restricted to a specific type in the service operation.  This may sound somewhat vague.  So, here is an example to provide a better illustration:

[DataContract]
public class MyGenericObject<T>
{
    private T _id;
    private string _description;

    public MyGenericObject()
    {
    }

    [DataMember]
    public T ID
    {
        get { return _id; }
        set { _id = value; }
    }

    [DataMember]
    public string Description
    {
        get { return _description; }
        set { _description = value; }
    }
}

Read more: Jeff W. Barnes
QR: Inline image 1

Posted via email from Jasper-Net