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!


3 comments:

  1. "basically it could have been something that inherits from DynamicObject and implements INotifyPropertyChanged/IErrorInfo and been a kickass dynamic data model"

    Could be work without seviceknowntypes?

    ReplyDelete
  2. @rat86 yes. It works without serviceknowntypes

    ReplyDelete
  3. I was using the dynamic "type" to build a service using WCF, but unfortunely it wont work for neither List or Dictionary types. Neither to serializable complex objects.

    Do you know any kind of configuration that i can use to achieve this?

    ReplyDelete