views:

13

answers:

1

I'm working on a Windows Phone 7 app using WCF for communications with my server.

I've created a service and am able to communicate well, but I'm having trouble accessing an interface in the client code.

For instance, in my server code I have something like this:

[OperationContract]
[ServiceKnownType(typeof(IField))]
[ServiceKnownType(typeof(TextField))]
[ServiceKnownType(typeof(NumberField))]
FieldForm GetForm();

Now my FieldForm contains the following declaration:

[DataContract]
class FieldForm
{
   public List<IField> Fields { get; set; }
}

And finally, this IField interface has a few implementations:

interface IField
{
   string Name { get; set; }
}

[DataContract]
class TextField : IField
{
}

[DataContract]
class NumberField : IField
{
}

(this isn't my code, but describes what I'm trying to accomplish)

Now on my client, I receive a FieldForm object via WCF and want to iterate through the Fields list to determine what UI elements to create. Problem is, the service did not provide the IField interface on the client, but I do have the implementations available (TextField and NumberField).

This leads to some crappy code in my client code like:

foreach ( object field in Fields )
{
   if ( field is TextField )
      // do textfieldy stuff
   else if (field is NumberField)
      // do numberfieldy stuff
}

when I'd really prefer to just use:

foreach ( IField field in Fields )
{
   field.Name;
}

Am I missing a simple annotation on the interface in order to make the interface type available on the client, or does WCF simply not provide the ability to serialize interfaces?

Is there a way I can access my interface in my client code?

+1  A: 

No you cannot serialize an interface across a WCF connection.

WCF uses serialized (XML) messages to communicate between client and server - all you can express in XML schema (XSD) can be moved across. This basically means any concrete type, composed of atomic types like int, string, etc.. XSD also supports inheritance and enums, but that's about the end of the flagpole.

What you might be able to do if you control both ends of the communications link (e.g. both server and client) is to put those interfaces (service interfaces and your data contracts and interfaces) into a common, shared assembly which both your client project and server project would then reference. Use any class implementing your interface in the concrete service implementation, but with this assembly sharing, you can use the signature you like on the client side and program against an interface. Mind you: this "kills" all interoperability of your WCF service - no Ruby or Java clients will be able to call your service anymore.

marc_s
Thanks! I really like the shared assembly idea, though that would be overkill for this particular project. I'll definitely remember that strategy for the future, though.
Stefan Mohr