.netwcfwcf-configurationknown-types

How do you configure WCF known types programmatically?


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.


Solution

  • Add [ServiceKnownType] to your [ServiceContract] interface:

    [ServiceKnownType("GetKnownTypes", typeof(KnownTypesProvider))]
    

    then create a class called KnownTypesProvider:

    internal static class KnownTypesProvider
    {
        public static IEnumerable<Type> GetKnownTypes(ICustomAttributeProvider provider)
        {
             // collect and pass back the list of known types
        }
    }
    

    and then you can pass back whatever types you need.