tags:

views:

75

answers:

2

I want to have an operation contract that returns an interface.

My problems:

1) I want to register dynamically with the service the known type that will be returned, or to have WCF accept the type. I noticed that unless it is a known type marked by attribute or in a static method of the service, the method will fail.

2) I want on the client side, to be able to construct a dynamic implementor of the interface from the message.

I don't want to mess with messages. I just want that the implementation details to be hidden.

+1  A: 

I've run into the same situation : I think you have, by design, to use the [KnownType] attribute so the serializer know which implementation to wait for.

The key point is that the serializer receives some bytes with only little metadata regarding how to read them (mainly, the type's name). That's why it needs to know which type those bytes are supposed to represent, and to "know" this type. Without this information, there's absolutely no way for the serializer to figure out where it's suppose to find the few fields implementing your interface functionality.

However, you can add new KnownTypes at runtime (ie dynamically) using directly the DataContractSerializer

Plenty of information on that topic here

Brann
A: 

You can implement a method that returns the known Types for a DataContract by using a specific overload of KnownTypeAttribute and provide it with the name of the method that returns the known Types as an array. The method can return types that are known only at runtime:

[DataContract]
[KnownType("GetKnownTypes")]
public class MyDataContract
{
   public int X { get; set; }

   public static Type[] GetKnownTypes()
   {
      return new Type[] { typeof(Class1), typeof(Class2) }; 
   }
}
Karl