Serialize delivered class's instance using DataContract

139 views Asked by At

I have library with class in it looks like next:

[DataContract]
class MyBaseClass
{
    public string Name { get; set; }
}

Also, I have another project with ref of this library and class in it looks like:

[DataContract]
class MyDeliveredClass : MyBaseClass
{
    public string SecondName { get; set; }
}

I wonder how could I serialize list<MyBaseClass> which could contain objects of MyBaseClassand MyDeliveredClass ?

May be I should use [KnownType(MyDeliveredClass)]... but I have no reference to MyDeliveredClass in library...

1

There are 1 answers

0
Ricibob On BEST ANSWER

If you declare both MyBaseClass and MyDeliveredClass as Service known types on the service contract interface then that should do the trick:

[ServiceContract(SessionMode = SessionMode.Required, ...)]
[ServiceKnownType(typeof(MyBaseClass ))]
[ServiceKnownType(typeof(MyDeliveredClass ))]
public interface IMySerivceContract {
    ...
}

Generally you have to choice between delclaring as KnownTypes on the class declaration or as ServerKnownTypes on the service interface. However sometimes the KnownType route is not an option for various reasons - one of which is your situation where you dont have access to a class declaration. Another case where you are forced to use ServiceKnownTypes is if your contract uses interfaces instead of the base class i.e if your contract had List<IMyBaseInterface>.