My client/server application is using WCF for communication, which has been great. However one shortcoming of the current architecture is that I must use known type configuration for certain transmitted types. I'm using an in-house Pub/Sub mechanism and this requirement is unavoidable.
The problem is that it's easy to forget to add the known type, and if you do, WCF fails silently with few clues as to what's going wrong.
In my application, I know the set of types that are going to be sent. I would like to perform the configuration programmatically, rather than declaratively through the App.config
file which currently contains something like this:
<system.runtime.serialization>
<dataContractSerializer>
<declaredTypes>
<add type="MyProject.MyParent, MyProjectAssembly">
<knownType type="MyProject.MyChild1, MyProjectAssembly"/>
<knownType type="MyProject.MyChild2, MyProjectAssembly"/>
<knownType type="MyProject.MyChild3, MyProjectAssembly"/>
<knownType type="MyProject.MyChild4, MyProjectAssembly"/>
<knownType type="MyProject.MyChild5, MyProjectAssembly"/>
</add>
</declaredTypes>
</dataContractSerializer>
</system.runtime.serialization>
Instead, I'd like to do something like this:
foreach (Type type in _transmittedTypes)
{
// How would I write this method?
AddKnownType(typeof(MyParent), type);
}
Can someone please explain how I might do this?
EDIT Please understand that I'm trying to set the known types dynamically at run time rather than declaratively in config or using attributes in the source code.
This is basically a question about the WCF API, not a style question.
EDIT 2 This MSDN page page states:
You can also add types to the ReadOnlyCollection, accessed through the KnownTypes property of the DataContractSerializer.
Unfortunately that's all it says and it doesn't make terribly much sense given that KnownTypes is a readonly property, and the property's value is a ReadOnlyCollection
.
I needed to do this to allow inheritance to work properly. I didn't want to have to maintain the list of derived types.
I know the first line of the function is overkill but it just means I can paste it into any base class without modification.
a bit overkill, but works and is kind of future proof
There are 2 additional ways to solve your problem:
I. Use KnownTypeAttribute(string):
II. Use constructor DataContractSerializer
NOTE: You must use this attribute on both sides: client side and service side!
Add
[ServiceKnownType]
to your[ServiceContract]
interface:then create a class called
KnownTypesProvider
:and then you can pass back whatever types you need.
Web .Config
The Order is the abstract base class