title: How do you deserialize an interface to an internal class of another assembly?
body: <p>Obviously, it is impossible to serialize/deserialize interfaces if the concrete types are <em>not known</em> to the compiler.</p>
  
  <p>I have an interface-only assembly <code>MyInterfaces</code> and an assembly <code>MyImpl</code> with <strong>internal</strong> implementations of these interfaces. Instantiation looks like this:</p>
  
  <pre><code>MyInterfaces.IFoo foo = MyImpl.FooFactory.CreateFoo();
  </code></pre>
  
  <p>Here's the factory in assembly <code>MyImpl</code>:</p>
  
  <pre><code>IFoo CreateFoo()
  {
      return new Foo(); // Internal class!
  }
  </code></pre>
  
  <p>And here's the concrete <code>Foo</code> class in assembly <code>MyImpl</code>:</p>
  
  <pre><code>[DataContract]
  internal class Foo : IFoo
  {
      [DataMember]
      public string Bar
      {
          get;
          set;
      }
  }
  </code></pre>
  
  <h2>Serialization is trivial</h2>
  
  <p>Reading the type of the factory-created <code>IFoo</code> object allows for serialization of the <code>IFoo</code> interface: </p>
  
  <pre><code>var serializer = new DataContractSerializer(typeof(MyFooContainer),
      new Type[] { container.Foo.GetType() });
  serializer.WriteObject(writer, container);
  </code></pre>
  
  <h2>Deserialization impossible?</h2>
  
  <p>When deserializing, the type cannot be deduced since we have no object to look at! </p>
  
  <pre><code>var serializer = new DataContractSerializer(typeof(MyFooContainer),
      new Type[] { /* CANNOT provide other assembly's internal type! */ });
  container = (MyFooContainer)serializer.ReadObject(reader);
  </code></pre>
  
  <p>I was hoping that the serialized XML would be enough for <code>DataContractSerializer</code> to determine how to create the <code>MyImpl.Foo</code> object, but no. It tells me this:</p>
  
  <p><em>"Error in line 1 position 269. Element '<a href="http://schemas.datacontract.org/2004/07/MyAssembly:Foo" rel="nofollow">http://schemas.datacontract.org/2004/07/MyAssembly:Foo</a>' contains data from a type that maps to the name '<a href="http://schemas.datacontract.org/2004/07/MyImpl:Foo" rel="nofollow">http://schemas.datacontract.org/2004/07/MyImpl:Foo</a>'. The deserializer has no knowledge..."</em></p>
  
  <p><strong>Q: Using <code>DataContractSerializer</code>, how do you deserialize an interface to an internal, derived class of another assembly?</strong></p>
  
  <p>Obviously, it makes sense to have public interfaces with internal implementations. It also makes sense to allow for serialization. Please help!</p>
  
  <p>More about this particular problem: <a href="http://blogs.msdn.com/b/sowmy/archive/2008/10/04/serializing-internal-types-using-xmlserializer.aspx" rel="nofollow">http://blogs.msdn.com/b/sowmy/archive/2008/10/04/serializing-internal-types-using-xmlserializer.aspx</a></p>