Andrey Khataev
Andrey Khataev

Reputation: 1343

DataContractSerializer. Serializing class through interface

I have class that implements some interface:

[DataContract]
public class ScriptState : IScriptState
{
   <...>
}

I have simple helper class

public class Serializer
{
  string Serialize<T>(T obj)
  {
     MemoryStream ms = new MemoryStream();
     DataContractSerializer ser = new DataContractSerializer(typeof(T));
     ser.WriteObject(ms, obj);
     <...>
  }
}

the problem is that I have loose coupled application and I get ScriptState object something like this:

IScriptstate ss = ServiceLocator.Resolve<IScriptState>();

i.e. variable has type of interface, and it is being processed by serializer:

Serializer.Serialize(ss);

and because of this DataContracrSerializer is instantiated with type of interface IScriptState, but real type of object is ScriptState, which leads to error, that type ScriptState is not expected.

Standard workaround should be adding knowntype ScriptState to interface IScriptState, but I can't do this obviously:

[KnownType(typeof(Scriptstate))]
IScriptState
{}

because assembly with interface has no reference to assembly with class.

Is there another solution??

Upvotes: 1

Views: 1618

Answers (1)

Andrey Khataev
Andrey Khataev

Reputation: 1343

I think I've found solution. In helper class use obj.GetType() instead of typeof(T) : DataContractSerializer ser = new DataContractSerializer(obj.GetType());

Upvotes: 2

Related Questions