Friday, April 1, 2011

How WCF will deal will dynamic

Yes. WCF can serialize dynamic as long as the underlying type passed as dynamic supports serialization.

This is soo cool.

So I made a test WCF project will the following Operation Contract in the Service Contract :

[OperationContract]
        dynamic AcceptDynamic(dynamic cool);
And the following service implementation: 
public dynamic AcceptDynamic(dynamic cool)
        {
            if (cool is string)
                return cool + " DAMN COOL";
            if (cool is int)
                return cool + 10;
            return "";
        }

After I import this at the client I get the following method signature: 
public object AcceptDynamic(object cool) {
            return base.Channel.AcceptDynamic(cool);
        }

Notice the dynamic has been changed to object. Means I pass in anything I want. It get stored in object. Serialized to server. Deserialized into dynamic. And used as necessary. In retrospect its obvious. But the repercussions for potentional dynamic service design are enormous. More on that latter (basically it could have been something that inherits from DynamicObject and implements INotifyPropertyChanged/IErrorInfo and been a kickass dynamic data model). 

Sample client:

static void Main(string[] args)
        {
            ServiceReference1.Service1Client svc = new ServiceReference1.Service1Client();
            Console.WriteLine(svc.AcceptDynamic("asdf"));
            Console.WriteLine(svc.AcceptDynamic(10));
        }

And the output: 
Enjoy!