开发者

Can I use an interface as a type in my WCF client code?

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开发者_JAVA百科 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?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜