6

I have an interface IServiceInfo and an abstract class ServiceInfo. There are several classes inherited from ServiceInfo, like CoreServiceInfo, ModuleServiceInfo etc. There is a service contract named RootService which returns IServiceInfo.

 public IServiceInfo GetServiceInfo()
 {
     return (IServiceInfo)new CoreServiceInfo();
 }

I am having problem serializing. I can use ServiceKnownType to identify base class, and KnownType to identify child class.

Problem is I do not know all the ServiceInfo child, since application can have plugins with different child inherited from ServiceInfo, so I cannot tell serializer to have all the child in serialized XML.

I can ignore abstract class, but it contains certain common implementation so I need to keep it. As a work around I can have another class say "sampleServiceInfo" and convert all the info classes to sampleServiceInfo and return it from Service method, and define KnownType to ServiceInfo class.

[KnownType(typeof(sampleServiceInfo))]
public class ServiceInfo : IServiceInfo

But that does not sound pretty way to do it. Please suggest. Do I need to write custom serializer? Is there any way to serialize base only and ignoring the child when both has same members?

Nate
  • 30,286
  • 23
  • 113
  • 184
hungryMind
  • 6,931
  • 4
  • 29
  • 45

1 Answers1

7

Get all the types in all loaded assemblies that implement given abstract class or interface(ref:Implementations of interface through Reflection)

 var allTypes =  AppDomain
            .CurrentDomain
            .GetAssemblies()
            .SelectMany(assembly => assembly.GetTypes())
            .Where(type => typeof(A).IsAssignableFrom(type));

Then create serializer passing allTypes as known types parameter, as below

var serializer = new DataContractSerializer(typeof(A), allTypes);

that's it - you will be able to serialize and deserialize any type that derives from A (A could be class or interface, if interface, serializer writes elements as deriving from xs:anyType.

Community
  • 1
  • 1
Om Deshmane
  • 808
  • 6
  • 11
  • Thanks mho, so finally i need to write custom serializer. I was expecting some class level attribute to ignore serialization, or some nice pattern, or something like that. Great and thanks anyway. – hungryMind Dec 21 '10 at 05:47
  • @hungryMind if that answered the question you would do well to mark it as such by checking the mark underneath the vote-spinner. – jcolebrand Dec 26 '10 at 15:43