I want to know as to how to configure known types in WCF. For example, I have a Person class and an Employee class. The Employee class is a sublass of the Person class. Both class are marked with a [DataContract]
attribute.
I dont want to hardcode the known type of a class, like putting a [ServiceKnownType(typeof(Employee))]
at the Person class so that WCF will know that Employee is a subclass of Person.
Now, I added to the host's App.config the following XML configuration:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.runtime.serialization>
<dataContractSerializer>
<declaredTypes>
<add type="Person, WCFWithNoLibrary, Version=1.0.0.0,Culture=neutral,PublicKeyToken=null">
<knownType type="Employee, WCFWithNoLibrary, Version=1.0.0.0,Culture=neutral, PublicKeyToken=null" />
</add>
</declaredTypes>
</dataContractSerializer>
</system.runtime.serialization>
<system.serviceModel>
.......
</system.serviceModel>
</configuration>
I compiled it, run the host, added a service reference at the client and added some code and run the client. But an error occured:
The formatter threw an exception while trying to deserialize the message: There was an error while trying to deserialize parameter
http://www.herbertsabanal.net:person
. The InnerException message was 'Error in line 1 position 247. Element'http://www.herbertsabanal.net:person'
contains data of the'http://www.herbertsabanal.net/Data:Employee'
data contract. The deserializer has no knowledge of any type that maps to this contract. Add the type corresponding to 'Employee' to the list of known types - for example, by using the KnownTypeAttribute attribute or by adding it to the list of known types passed to DataContractSerializer.'. Please see InnerException for more details.
Below are the data contracts:
[DataContract(Namespace="http://www.herbertsabanal.net/Data", Name="Person")]
class Person
{
string _name;
int _age;
[DataMember(Name="Name", Order=0)]
public string Name
{
get { return _name; }
set { _name = value; }
}
[DataMember(Name="Age", Order=1)]
public int Age
{
get { return _age; }
set { _age = value; }
}
}
[DataContract(Namespace="http://www.herbertsabanal.net/Data", Name="Employee")]
class Employee : Person
{
string _id;
[DataMember]
public string ID
{
get { return _id; }
set { _id = value; }
}
}
Btw, I didn't use class libraries (WCF class libraries or non-WCF class libraries) for my service. I just plain coded it in the host project.
I guess there must be a problem at the config file (please see config file above). Or I must be missing something. Any help would be pretty much appreciated.