object reference not set to an instance of an object" - Not "initialized" through WCF?
-
Could one please give me a hit, or probably confirm a bug?
I have a custom class, something like this:
[DataContract]
public class CompositeType
{
ClassX x = new ClassX();
[DataMember]
public string Field
{
get { return x.X; }
set { x.X = value; }
}
}
public class ClassX
{
public string X;
}
When used in a WCF service, I get a "object reference not set to an instance of an object". I have also tried using a class initializer (public CompositeType()), where I do the new ClassX(); but I do get the same result...
Does anyone know why? Is there a solution for it?
Thankx, Cheers Harry
Answers
-
On deserialization, WCF does not call the constructors or field initializers of the type it's creating. If you need to perform some initialization on deserialization, you need to use the OnDeserializing callback (http://msdn2.microsoft.com/en-us/library/system.runtime.serialization.ondeserializingattribute.aspx). The example below should work for you:
[DataContract]
public class CompositeType
{
ClassX x;
[DataMember]
public string Field
{
get { return x.X; }
set { x.X = value; }
}
public CompositeType()
{
Initialize();
}
[OnDeserializing]
public void OnDeserializing(StreamingContext ctx)
{
Initialize();
}
private void Initialize()
{
this.x = new ClassX();
}
}
public class ClassX
{
public string X;
}