views:

2361

answers:

2

I am trying to define a WCF contract that returns an interface, something like below:

[ServiceContract]
public interface IMyContracts
{
    [OperationContract]
    IMyInterface GetData(string request);
}

To get this to work I think my interface (IMyInterface) would have to implement ISerializable to ensure classes implementing my interface can be serialized. This then means I have to manually implement serialization for any classes implementing my interface.

It seems that either I use my interface and risk runtime errors if a class is used that is not serializable, or I make the interface implement ISerializable and have the associated hassle of manual implementation.

Am I confusing myself and missing something obvious? How have other people returned interfaces using WCF and avoided this problem?

Thanks very much.

+7  A: 

AFAIK, the problem is not with serialization but with the fact that you're returning abstract entity (an interface). Abstraction is an OO concept, not SOA concept. So, your client's wcf stack may not know what to do with the class behind the interface. What if the client does not know the class behind the interface. Client's WCF stack must deserialize it, and to do it, it must know the class.

So, you must make the class(es) behind the interface part of your contract, via KnownTypeAttribute.

You may also use ServiceKnownTypeAttribute class that seems to be more flexible. Still, remember that the client must know the type, or you'll get an exception.

Krzysztof Koźmic
Take a look at Exchange Web Service : http://msdn.microsoft.com/en-us/library/bb204119.aspx, it uses polymorphism heavily.This is not a simple web service to use but it is very powerfull and coarse grained.
Nicolas Dorier
+1  A: 

In this post, I go into details of how to make WCF work for receiving and returning derived classes and interfaces.

http://coab.wordpress.com/2010/03/01/serializing-and-deserializing-derived-types-or-interfaces-in-wcf/

floatingfrisbee