title: How do you configure WCF known types programmatically?
body: <p>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.</p>
  
  <p>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.</p>
  
  <p>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 <code>App.config</code> file which currently contains something like this:</p>
  
  <pre><code>&lt;system.runtime.serialization&gt;
    &lt;dataContractSerializer&gt;
      &lt;declaredTypes&gt;
        &lt;add type="MyProject.MyParent, MyProjectAssembly"&gt;
          &lt;knownType type="MyProject.MyChild1, MyProjectAssembly"/&gt;
          &lt;knownType type="MyProject.MyChild2, MyProjectAssembly"/&gt;
          &lt;knownType type="MyProject.MyChild3, MyProjectAssembly"/&gt;
          &lt;knownType type="MyProject.MyChild4, MyProjectAssembly"/&gt;
          &lt;knownType type="MyProject.MyChild5, MyProjectAssembly"/&gt;
        &lt;/add&gt;
      &lt;/declaredTypes&gt;
    &lt;/dataContractSerializer&gt;
  &lt;/system.runtime.serialization&gt;
  </code></pre>
  
  <p>Instead, I'd like to do something like this:</p>
  
  <pre><code>foreach (Type type in _transmittedTypes)
  {
      // How would I write this method?
      AddKnownType(typeof(MyParent), type);
  }
  </code></pre>
  
  <p>Can someone please explain how I might do this?</p>
  
  <p><strong>EDIT</strong> 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.</p>
  
  <p>This is basically a question about the WCF API, not a style question.</p>
  
  <p><strong>EDIT 2</strong> <a href="http://msdn.microsoft.com/en-us/library/ms730167.aspx" rel="noreferrer">This MSDN page</a> page states:</p>
  
  <blockquote>
    <p>You can also add types to the ReadOnlyCollection, accessed through the KnownTypes property of the DataContractSerializer. </p>
  </blockquote>
  
  <p>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 <code>ReadOnlyCollection</code>.</p>